Cra*_*een 20 python byte bytearray python-2.x python-3.x
我在Python 2.6中尝试使用bytesvs.bytearray我不明白一些差异的原因.
一个bytes迭代器返回的字符串:
for i in bytes(b"hi"):
print(type(i))
Run Code Online (Sandbox Code Playgroud)
得到:
<type 'str'>
<type 'str'>
Run Code Online (Sandbox Code Playgroud)
但bytearray迭代器返回ints:
for i in bytearray(b"hi"):
print(type(i))
Run Code Online (Sandbox Code Playgroud)
得到:
<type 'int'>
<type 'int'>
Run Code Online (Sandbox Code Playgroud)
为什么不同?
我想编写能够很好地转换为Python 3的代码.那么,Python 3中的情况是否相同?
TL; 博士
python2.6+
bytes= python2.6+str= python3.xbytes!= python3.xstrpython2.6+
bytearray= python3.xbytearraypython2.x
unicode= python3.xstr
长答案
bytes并且str从 python 3.x 开始改变了 python 中的含义。
首先简短地回答您的问题,在python 2.6 中bytes(b"hi")是一个不可变的字节数组(8 位或八位字节)。所以 each 的类型byte是simple ,这和 python 2.6+ 中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
Run Code Online (Sandbox Code Playgroud)
现在 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
Run Code Online (Sandbox Code Playgroud)
bytes并且bytearray在 python 3.x 中是相同的,除了可变性。
str你可能会问发生了什么事?str在 python 3 中被转换为unicodepython 2 中的内容,并且unicode随后从 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中被混淆地称为类型,unicode在python 2中称为类型)。