考虑以下打字脚本:
>>> s = 'a'
>>> isinstance(s, bytes)
True
>>> isinstance(s, str)
True
>>> isinstance(s, unicode)
False
>>> isinstance(s.decode('utf-8'), unicode)
True
为什么s
既是str
又是bytes
?其中一个是另一个的后代吗?
我是怎么碰到它的?我试图在文档中找到decode
方法的描述。我找不到str
,但可以为bytes
。
你看错文档了。
此等价仅在Python 2.7中为真。在那里,bytes
作为str
的别名被引入,以方便迁移到Python 3。
在Python 3中,str
是以前称为unicode
的类型,bytes
是以前称为str
的类型。
str.decode
for Python 2的文档在这里