make python默认用字符串替换不可编码的字符

ola*_*ndo 7 python encode replace

我想通过简单地用字符串替换它们来使python忽略字符无法编码"<could not encode>".

例如,假设默认编码是ascii,命令

'%s is the word'%'ébác'
Run Code Online (Sandbox Code Playgroud)

会屈服

'<could not encode>b<could not encode>c is the word'
Run Code Online (Sandbox Code Playgroud)

在我的所有项目中,有没有办法使这成为默认行为?

mik*_*iku 11

str.encode函数采用定义错误处理的可选参数:

str.encode([encoding[, errors]])
Run Code Online (Sandbox Code Playgroud)

来自文档:

返回字符串的编码版本.默认编码是当前的默认字符串编码.可以给出错误以设置不同的错误处理方案.错误的默认值是'strict',这意味着编码错误会引发UnicodeError.其他可能的值是'ignore','replace','xmlcharrefreplace','backslashreplace'以及通过codecs.register_error()注册的任何其他名称,请参阅Codec Base Classes部分.有关可能的编码列表,请参阅标准编码部分.

在您的情况下,该codecs.register_error功能可能是有意义的.

[关于坏字符的注意事项]

顺便说一下,注意使用register_error它时你可能会发现自己不仅仅用个字符串替换单个坏字符,而是用你的字符串替换连续坏字符组,除非你注意.每次运行坏字符时都会调用错误处理程序,而不是每个字符.


J.J*_*.J. 5

>>> help("".encode)
Help on built-in function encode:

encode(...)
S.encode([encoding[,errors]]) -> object

Encodes S using the codec registered for encoding. encoding defaults
to the default encoding. errors may be given to set a different error
handling scheme. Default is 'strict' meaning that encoding errors raise
a UnicodeEncodeError. **Other possible values are** 'ignore', **'replace'** and
'xmlcharrefreplace' as well as any other name registered with
codecs.register_error that is able to handle UnicodeEncodeErrors.
Run Code Online (Sandbox Code Playgroud)

所以,例如:

>>> x
'\xc3\xa9b\xc3\xa1c is the word'
>>> x.decode("ascii")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
>>> x.decode("ascii", "replace")
u'\ufffd\ufffdb\ufffd\ufffdc is the word'
Run Code Online (Sandbox Code Playgroud)

将您自己的回调添加到codecs.register_error以替换为您选择的字符串.