TL;博士
python2.6+ bytes
= python2.6+ str
= python3.x bytes
!= python3.xstr
python2.6+ bytearray
= python3.xbytearray
python2.x unicode
= python3.xstr
长答案
bytes
并且str
自 python 3.x 以来在 python 中的含义发生了变化。
首先要简短回答您的问题,在 python 2.6bytes(b"hi")
中是一个不可变的字节数组(8 位或八位字节)。所以 each 的类型byte
是byte
中的相同str
(但是,python 3.x 中不是这种情况)
bytearray(b"hi")
又是一个可变的字节数组。但是当您询问它的类型时,它是int
,因为 python 将 的每个元素表示bytearray
为 0-255 范围内的整数(8 位整数的所有可能值)。但是,bytes
数组的元素表示为该字节的 ASCII 值。
例如,考虑在Python 2.6+
>>> barr=bytearray(b'hi')
>>> bs=bytes(b'hi')
>>> barr[0] # python shows you an int value for the 8 bits 0110 1000
104
>>> bs[0] # python shows you an ASCII value for the 8 bits 0110 1000
'h'
>>> chr(barr[0]) # chr converts 104 to its corresponding ASCII value
'h'
>>> bs[0]==chr(barr[0]) # python compares ASCII value of 1st byte of bs and ASCII value of integer represented by first byte of barr
True
现在 python 3.x 是一个完全不同的故事。正如您可能已经猜到的那样,为什么在 python2.6+ 中str
文字意味着 a是很奇怪的。byte
那么这个答案解释了
在 Python 3.x 中,anstr
是一个 Unicode 文本(以前只是一个字节数组,注意 Unicode 和字节是两个完全不同的东西)。bytearray
是一个可变的字节数组,而bytes
是一个不可变的字节数组。它们都具有几乎相同的功能。现在,如果我在 python 3.x 中再次运行上述相同的代码,结果如下。在Python 3.x中
>>> barr=bytearray(b'hi')
>>> bs=bytes(b'hi')
>>> barr[0]
104
>>> bs[0]
104
>>> bs[0]==barr[0] # bytes and bytearray are same thing in python 3.x
True
bytes
并且bytearray
在 python 3.x 中是相同的,除了可变性。
你可能会问发生了什么事str
?str
在 python 3 中被转换为unicode
python 2 中的内容,并且unicode
type 随后从 python 3 中删除,因为它是多余的。
我想编写可以很好地转换为 Python 3 的代码。那么,Python 3 中的情况是否相同?
这取决于你想要做什么。您是在处理字节还是在处理字节的 ASCII 表示?
如果您正在处理 bytes,那么我的建议是bytearray
在 Python 2 中使用,这在 python 3 中是相同的。但是如果这对您来说很重要,那么您会失去不变性。
如果您正在处理 ASCII 或 text,则将您的字符串表示为u'hi'
在 Python 2 中,这在 python 3 中具有相同的含义。'u'
在 Python 2 中具有特殊含义,它指示 python 2 将字符串文字视为unicode
类型。python 3 中的 'u' 没有意义,因为默认情况下 Python 3 中的所有字符串文字都是 Unicode(str
在 python 3 中被混淆地称为 type,unicode
在 python 2 中称为 type)。