python-3.x - 在 Python 3 中,当我索引字节数组时会发生什么?

标签 python-3.x character-encoding bytearray

在 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/

相关文章:

Python 3 UnicodeDecodeError - 如何调试 UnicodeDecodeError?

mysql - 如何将整个 MySQL 数据库字符集和排序规则转换为 UTF-8?

python - 如何检测双字节数字

c# - 在 C# 中将 3 个字节转换为有符号整数

python - 有什么方法可以使用列表理解从列表中创建集合吗?

python - 为每个客户查找日期时间的缺失值

python - 为什么 Tkinter 的 askdirectory() 在 Windows 上返回正斜杠?

python - python 类型注释的参数化联合

python - 如何复制 python bytearray 缓冲区?

python - 将字节串转换为字节或字节数组