In Python 3, I can create a bytearray by encoding a string:
在Python 3中,我可以通过编码字符串来创建bytearray:
>>> foo = 'abc'
>>> bar = foo.encode('utf-8')
>>> bar
b'abc'
But when I index that byte array, I get something else:
但是当我索引那个字节数组时,我得到了别的东西:
>>> bar[0]
97
What is this and why isn't it
这是什么,为什么不是
b'a'
3 个解决方案
#1
2
It's a small int, because that's how indexing bytes is defined in PEP 3137: "Immutable Bytes and Mutable Buffer".
这是一个很小的整数,因为这就是在PEP 3137中定义字节的方式:“不可变字节和可变缓冲区”。
Indexing
Indexing bytes and bytearray returns small ints [...]
索引字节和bytearray返回小ints[…]
Assignment to an item of a bytearray object accepts an int in range(256). [...]
一个bytearray对象的项的赋值接受一个范围内的整数(256)。[…]
If you want b'a'
then slice instead.
如果你想要b' '然后切片代替。
3>> b'abc'[0:1]
b'a'
#2
1
Byte arrays are data, not characters, so individual elements are values 0-255.
字节数组是数据,而不是字符,因此单个元素的值为0-255。
#3
1
The value 97 is the UTF-8 encoding of the character a
. Most common characters are encoded in UTF-8 in the same way they are encoded in ASCII.
值97是字符a的UTF-8编码。大多数常用字符都是用UTF-8编码的,就像用ASCII编码一样。
#1
2
It's a small int, because that's how indexing bytes is defined in PEP 3137: "Immutable Bytes and Mutable Buffer".
这是一个很小的整数,因为这就是在PEP 3137中定义字节的方式:“不可变字节和可变缓冲区”。
Indexing
Indexing bytes and bytearray returns small ints [...]
索引字节和bytearray返回小ints[…]
Assignment to an item of a bytearray object accepts an int in range(256). [...]
一个bytearray对象的项的赋值接受一个范围内的整数(256)。[…]
If you want b'a'
then slice instead.
如果你想要b' '然后切片代替。
3>> b'abc'[0:1]
b'a'
#2
1
Byte arrays are data, not characters, so individual elements are values 0-255.
字节数组是数据,而不是字符,因此单个元素的值为0-255。
#3
1
The value 97 is the UTF-8 encoding of the character a
. Most common characters are encoded in UTF-8 in the same way they are encoded in ASCII.
值97是字符a的UTF-8编码。大多数常用字符都是用UTF-8编码的,就像用ASCII编码一样。