为什么以下项目失败?为什么使用“latin-1”编解码器会成功?
o = "a test of \xe9 char" #I want this to remain a string as this is what I am receiving
v = o.decode("utf-8")
结果是:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\encodings\utf_8.py",
line 16, in decode
return codecs.utf_8_decode(input, errors, True) UnicodeDecodeError:
'utf8' codec can't decode byte 0xe9 in position 10: invalid continuation byte
原文由 RuiDC 发布,翻译遵循 CC BY-SA 4.0 许可协议
在二进制中,0xE9 看起来像
1110 1001
。如果您 在 Wikipedia 上阅读过有关 UTF-8 的内容,您会发现这样的字节后面必须跟有两个形式10xx xxxx
。所以,例如:但这只是异常的机械原因。在这种情况下,您有一个字符串几乎肯定是用 latin 1 编码的。您可以看到 UTF-8 和 latin 1 看起来有何不同:
(注意,我在这里混合使用了 Python 2 和 3 表示。输入在任何版本的 Python 中都有效,但您的 Python 解释器不太可能以这种方式实际显示 unicode 和字节字符串。)