为什么对字符串进行编码会导致解码错误(UnicodeDecodeError)?

33 浏览
0 Comments

为什么对字符串进行编码会导致解码错误(UnicodeDecodeError)?

我很困惑。我试图进行编码,但错误显示为无法解码……

>>> "你好".encode("utf8")
Traceback (most recent call last):
File "", line 1, in 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)

我知道如何通过在字符串前加上 "u" 前缀来避免这个错误。我只是想知道为什么在调用编码时会出现 "无法解码" 的错误。在幕后,Python是怎么做的?

0