【发布时间】:2011-09-30 09:27:52
【问题描述】:
我经常使用包含以下字符的 utf-8 文本:
\xc2\x99
\xc2\x95
\xc2\x85
等
这些字符混淆了我使用的其他库,因此需要替换。
什么是执行此操作的有效方法,而不是:
text.replace('\xc2\x99', ' ').replace('\xc2\x85, '...')
【问题讨论】:
-
您要允许哪些字符?仅 ASCII 码?
-
我仍然使用 unicode,但是有些字符会导致库中出现需要替换的字符
-
我相信你会想按照docs.python.org/library/stdtypes.html#str.translate使用
text.translate(table) -
@TryPyPy:让你的评论成为答案,这样我就可以投票了。您可能还想提及 Python 3+ 也有
str.maketrans()。 -
str.translate() 仅适用于单字节字符
标签: python string unicode replace