gpt4 book ai didi

python - 为什么类型(字节())<'str' >

转载 作者:太空狗 更新时间:2023-10-29 22:04:50 25 4
gpt4 key购买 nike

我是 python 的新手,我很欣赏它是一种动态语言。在我编写第一个 Python 代码大约 30 分钟后,我发现 bytes 类型的行为有点奇怪(至少可以这么说):

a = bytes()
print type(a)
// prints: <type 'str'>

在这里试试: http://ideone.com/NqbcHk

现在,docsstringsbytes 除了 .format.encode 表现非常相似,但我没想到他们是同一类型。我想确保的是我在代码中使用真实字节,并且不会发生强制转换/编码/解码。

那么这里发生了什么?

最佳答案

bytes 类型是 Python 3.x 中的新类型。在 Python 2.x 中,作为兼容性垫片,bytesstr 的简单别名。

在这里阅读更多相关信息:https://docs.python.org/2/whatsnew/2.6.html#pep-3112-byte-literals

Python 3.0 adopts Unicode as the language’s fundamental string type and denotes 8-bit literals differently, either as b'string' or using a bytes constructor. For future compatibility, Python 2.6 adds bytes as a synonym for the str type, and it also supports the b'' notation.

The 2.6 str differs from 3.0’s bytes type in various ways; most notably, the constructor is completely different. In 3.0, bytes([65, 66, 67]) is 3 elements long, containing the bytes representing ABC; in 2.6, bytes([65, 66, 67]) returns the 12-byte string representing the str() of the list.

The primary use of bytes in 2.6 will be to write tests of object type such as isinstance(x, bytes). This will help the 2to3 converter, which can’t tell whether 2.x code intends strings to contain either characters or 8-bit bytes; you can now use either bytes or str to represent your intention exactly, and the resulting code will also be correct in Python 3.0.

关于python - 为什么类型(字节())<'str' >,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24633024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com