【问题标题】:ascii characters in a string-How to remove them字符串中的 ascii 字符-如何删除它们
【发布时间】:2015-01-29 14:21:52
【问题描述】:

我正在尝试加密文本,但遇到以下问题:

我有一个巨大的字符串(大约 500 多页串联在一起),其中包含以下形式的字符:

÷ΆώϋⁿΪⁿ÷ό±όⁿΈϊ÷ωΪⁿάⁿ÷ώ÷Ύ≤÷ώ

我需要从我的字符串中删除这些字符,只是我不知道怎么做。 假设这个大字符串被称为data。 我正在尝试以下方法:

for i in data:
   if i not in string.ascii_letters and i not in n and i not in string.punctuation and i !=' ':
      data.replace(i,"")

但是,它不起作用,因为之后我使用以下命令:

q=''
for i in data:
    if i not in string.ascii_letters and i not in n and i not in string.punctuation and i !=' ':
        q=q+i
print q

÷ΆώϋⁿΪⁿ÷ό±όⁿΈϊ÷ωΪⁿάⁿ÷ώ÷Ύ≤÷ώ 再次打印出来。

【问题讨论】:

  • 您是否要从密文中删除某些字符?
  • 只是一个离题的建议;请改用if letter not in (string.ascii_letters, string.punctuation, ' ')。这不是您的实际问题;下面的 Kevin 描述了您的问题。

标签: python string cryptography ascii non-ascii-characters


【解决方案1】:
  data.replace(i,"")

replace 不会修改data,它会创建一个新的字符串实例并返回它。尝试将结果分配回data

  data = data.replace(i,"")

【讨论】:

    【解决方案2】:

    这是删除非ASCII的完整代码:

    # -*- coding: UTF-8 -*-
    data = 'poqwe÷ΆώϋⁿΪⁿbar÷ό±όⁿΈϊfoo÷ωΪⁿάⁿ÷ώ÷Ύ≤÷ώ42'
    def remove_non_ascii(data):
        return ''.join([i if ord(i) < 128 else '' for i in data])
    data = remove_non_ascii(data)
    print data
    

    使用简单的 for 循环,它看起来像:

    # -*- coding: UTF-8 -*-
    data = 'poqwe÷ΆώϋⁿΪⁿbar÷ό±όⁿΈϊfoo÷ωΪⁿάⁿ÷ώ÷Ύ≤÷ώ42'
    def remove_non_ascii(data):
        foo = ''
        for i in data:
            if (ord(i) < 128):
                foo += i
            else:
                foo += '' # whatever you wanna put instead of non-ascii
        return foo 
    data = remove_non_ascii(data)
    print data
    

    【讨论】:

      猜你喜欢
      • 2012-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-27
      • 2016-02-01
      • 2023-03-18
      相关资源
      最近更新 更多