3 回答

TA贡献1712条经验 获得超3个赞
decodeUnicode字符串的方法实际上根本没有任何应用程序(除非出于某种原因在Unicode字符串中包含一些非文本数据,请参见下文)。我认为主要是出于历史原因。在Python 3中,它完全消失了。
unicode().decode()将执行隐式编码的s使用默认(ASCII)编解码器。像这样验证:
>>> 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类型,这不再是问题。
添加回答
举报