删除包含ASCII的字符串

时间:2013-05-26 05:32:40

标签: python python-3.x ascii

我有一串包含非ASCII字符的字符串,我想将其删除。我在Python 3中使用了以下函数:

def removeNonAscii(s): 
    return "".join(filter(lambda x: ord(x)<128, s))

str1 = "Hi there!\xc2\xa0My\xc2\xa0name\xc2\xa0is\xc2\xa0Blue "
new = removeNonAscii(str1)

新字符串变为:

  

你好!MynameisBlue

是否可以在字符串之间获取空格,使其为:

  你好!我的名字是Blue

2 个答案:

答案 0 :(得分:3)

下面的代码等同于您当前的代码,但对于US-ASCII范围之外的连续字符序列,它将用单个空格(ASCII 32)替换整个序列。

import re
re.sub(r'[^\x00-\x7f]+', " ", inputString)

请注意上面的代码允许控制字符,以及问题中的代码。

答案 1 :(得分:0)

regex在这里胜出,但FWIW在这里是一个itertools.groupby解决方案:

from itertools import groupby
text = "Hi there!\xc2\xa0My\xc2\xa0name\xc2\xa0is\xc2\xa0Blue "
def valid(c):
    return ord(c) < 128

def removeNonAscii(s):
    return ''.join(''.join(g) if k else ' ' for k, g in groupby(s, valid))

>>> removeNonAscii(text)
'Hi there! My name is Blue '