TL;DR
python2.6+ bytes = python2.6+ str = python3.x bytes != python3.x str
python2.6+ bytearray = python3.x bytearray
python2.x unicode = python3.x str
长答案
bytes 和 str 自 python 3.x 以来在 python 中的含义发生了变化。
首先回答您的问题,在 python 2.6 中,bytes(b"hi") 是一个不可变的字节数组(8 位或八位字节)。所以每个byte的类型就是byte,和python 2.6+中的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 是一个完全不同的故事。正如您可能已经猜到的那样,为什么str 文字在 python2.6+ 中意味着 byte 很奇怪。嗯this answer explains that
在 Python 3.x 中,str 是一个 Unicode 文本(以前只是一个字节数组,请注意 Unicode 和字节是两个完全不同的东西)。 bytearray 是 mutable 字节数组,而 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 发生了什么? python 3 中的 str 被转换为 python 2 中的 unicode ,而unicode 类型随后被从 python 3 中删除,因为它是多余的。
我想编写可以很好地转换为 Python 3 的代码。那么,Python 3 中的情况是否相同?
这取决于你想要做什么。你是处理字节还是处理字节的 ASCII 表示?
如果您正在处理字节,那么我的建议是在 Python 2 中使用 bytearray,这在 Python 3 中是相同的。但是如果这对您来说很重要,那么您会失去不变性。
如果你处理的是 ASCII 或文本,那么在 Python 2 中将你的字符串表示为 u'hi',在 Python 3 中具有相同的含义。'u' 在 Python 2 中具有特殊含义,它指示 python 2 将字符串文字视为 unicode 类型。 'u' 在 python 3 中没有意义,因为默认情况下 Python 3 中的所有字符串文字都是 Unicode(在 python 3 中被混淆地称为 str 类型,在 python 2 中称为 unicode 类型)。