我有这个代码
att=att.replace("à","a")
但是我收到了这个错误...
att=att.replace("à","a")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
我该如何解决?
最佳答案
不要将 unicode 与字节字符串混合。 Python2 进行隐式转换,而 Python3 则不进行。即使您不使用 Python3,避免混合两者也是一个好习惯。
在Python2中,如果att
是unicode,那么
att.replace("à","a")
在尝试之前会隐式尝试将“à”
和“a”
解码为unicode替换 att
中的 "à"
。
Python2 使用 ascii
(默认情况下)进行隐式解码。
"à".decode('ascii')
引发 UnicodeDecodeError: 'ascii' 编解码器无法解码位置 0 中的字节 0xc3:序数不在范围内(128)
.
要修复此错误,由于 att
是 unicode
,因此 att.replace
的参数也应该是 unicode:
att.replace(u"à",u"a")
关于Python 字符串编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32056220/