今天早些时候一位同事问我这个问题,我想不出一个合理的答案。 S/O 似乎有一些接近的答案,但我找不到具体回答这个问题的东西。
如果我在 64 位 Ubuntu 12.04 上使用 2.7x 解释器运行它,我得到:
>>> u'\u1234'.decode('utf-8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u1234' in position 0: ordinal not in range(128)
Python docs on the subject表示 Python 将 Unicode 字符串表示为 16 位或 32 位整数。使用 utf-8 解码时,Python 是否会尝试读取这些整数,就像使用 utf-8 编码的 8 位字符一样?如果是这样,为什么错误是 UnicodeEncodeError 而不是 UnicodeDecodeError?
我很想对此有更好的理解。对 Unicode 字符串调用解码时执行的步骤是什么?我不清楚用 utf-8 解码已经从其 utf-8 编码解码的字符串的含义。
请您参考如下方法:
这是一个 Python 2 疣。在使用指定编码重新解码之前,首先使用默认编码对 Unicode 字符串调用解码编码。由于默认编码通常是 ASCII,因此您会看到错误。
