decode
方法用于 Unicode 字符串几乎没有任何应用(除非你有一些非文本数据在 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()
是多余的。
但是后一种方法还有另一个有用的应用:存在一些与字符集无关的编码方式,因此可以有意义地应用于8位字符串:
>>> s.encode('zip')
'x\x9c;\xbc\r\x00\x02>\x01z'
你说得对:在这两个应用程序中,"编码"这个词的含义不明确是很尴尬的。然而,在Python 3中,有单独的byte
和string
类型,这个问题就不存在了。