我需要将一些非ASCII字符替换为“_”。
例如,Tannh‰user -> Tannh_user
- 如果我使用Python正则表达式,我该怎么做?
- 有没有更好的方法来替换而不使用正则表达式?
re.sub(r'[^\x00-\x7F]', '_', theString)
如果theString是Unicode,或者是ASCII占据值0至0x7F的编码字符串(如Latin-1、UTF-8等),则此方法可行。
'[\u0080-\uFFFF]'
将匹配第一个128个字符范围之外的任何UTF-8字符
re.sub('[\u0080-\uFFFF]+', '_', x)
将替换任何连续的非ASCII字符序列为下划线
已更新至Python 3:
>>> 'Tannh‰user'.encode().decode('ascii', 'replace').replace(u'\ufffd', '_')
'Tannh___user'
首先使用encode()
创建字节串-它默认使用UTF-8编解码器。如果您已经有了字节串,则可以跳过此编码步骤。
然后使用ascii编解码器将其转换为“普通”字符串。
这利用了UTF-8的特性,即所有非ASCII字符都被编码为值>= 0x80的字节序列。
Python 2的原始答案:
如何使用内置的str.decode
方法来实现:
>>> 'Tannh‰user'.decode('ascii', 'replace').replace(u'\ufffd', '_')
u'Tannh___user'
>>> s = 'Tannh‰user' # or u'Tannh‰user' in Python 2
>>>
>>> ''.join(c if ord(c) < 128 else '_' for c in s)
'Tannh_user'
利用Python对字符编码的支持:
# coding: utf8
import codecs
def underscorereplace_errors(exc):
return (u'_', exc.end)
codecs.register_error('underscorereplace', underscorereplace_errors)
print u'Tannh‰user'.encode('ascii', 'underscorereplace')
我更愿意对字符串中的每个字符都调用ord
函数,逐个检查。如果 ord([char]) >= 128
,那么该字符不是ASCII字符,需要进行替换。
[ -~]
,可以解决它:import re
re.sub(r"[^ -~]", "_", "Tannh‰user")
# 'Tannh_user'
[ -~]
可以捕获所有ASCII字符^
,我们可以捕获所有非ASCII字符mystring.replace('oldchar', 'newchar')
ord(item)> 127
。 然后,想想你的代码对于这个字符串 '\xa0'*1000
做了什么。 - tzot'\xa0'*1000
示例中,您的代码执行了整个mystring
替换一千次,其中有999次是不必要的。如果您不同意此事,则在给定astr ='hello'; c = 0的情况下,循环后c的值是多少:“for char in astr:c + = 1; astr ='”?我说它将是5,而您可能认为它将是1。 - tzot