python中的str和字节是什么关系?



考虑以下打字脚本:

>>> 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的文档在这里

最新更新