在 Python 3 中,我可以通过对字符串进行编码来创建字节数组:
>>> foo = 'abc'
>>> bar = foo.encode('utf-8')
>>> bar
b'abc'
但是当我索引那个字节数组时,我得到了其他东西:
>>> bar[0]
97
这是什么,为什么不是
b'a'
最佳答案
这是一个小整数,因为这就是在 PEP 3137: "Immutable Bytes and Mutable Buffer" 中定义索引字节的方式.
Indexing
Indexing bytes and bytearray returns small ints [...]
Assignment to an item of a bytearray object accepts an int in range(256). [...]
如果您想要 b'a'
则改为切片。
3>> b'abc'[0:1]
b'a'
关于python-3.x - 在 Python 3 中,当我索引字节数组时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24878265/