unicode 字符串的decode 方法实际上根本没有任何应用程序(除非您出于某种原因在 unicode 字符串中有一些非文本数据——见下文)。我认为这主要是出于历史原因。在 Python 3 中它完全消失了。
unicode().decode() 将使用默认 (ascii) 编解码器执行 s 的隐式编码。像这样验证:
>>> s = u'ö'
>>> s.decode()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 0:
ordinal not in range(128)
>>> s.encode('ascii')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 0:
ordinal not in range(128)
错误信息完全相同。
对于str().encode(),情况正好相反——它尝试使用默认编码对s 进行隐式解码:
>>> s = 'ö'
>>> s.decode('utf-8')
u'\xf6'
>>> s.encode()
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)
这样用str().encode()也是多余的。
但是后一种方法的另一个应用是有用的:有 encodings 与字符集无关,因此可以有意义地应用于 8 位字符串方式:
>>> s.encode('zip')
'x\x9c;\xbc\r\x00\x02>\x01z'
不过,您是对的:对于这两个应用程序,“编码”的模棱两可的用法是……很尴尬。同样,在 Python 3 中使用单独的 byte 和 string 类型,这不再是问题。