python - 为什么我在索引字节时会得到一个 int?

标签 python python-3.x

我试图在 python 3.4 中获取字节字符串的第一个字符,但是当我索引它时,我得到一个 int:

>>> my_bytes = b'just a byte string'
b'just a byte string'
>>> my_bytes[0]
106
>>> type(my_bytes[0])
<class 'int'>

这对我来说似乎不直观,因为我期望得到 b'j'

我发现我可以得到我期望的值(value),但对我来说这就像一个黑客攻击。

>>> my_bytes[0:1]
b'j'

谁能解释一下为什么会这样?

最佳答案

bytes类型是 Binary Sequence type , 并明确记录为包含 0 到 255 范围内的整数序列。

来自文档:

Bytes objects are immutable sequences of single bytes.

[...]

While bytes literals and representations are based on ASCII text, bytes objects actually behave like immutable sequences of integers, with each value in the sequence restricted such that 0 <= x < 256[.]

[...]

Since bytes objects are sequences of integers (akin to a tuple), for a bytes object b, b[0] will be an integer, while b[0:1] will be a bytes object of length 1. (This contrasts with text strings, where both indexing and slicing will produce a string of length 1).

我的大胆强调。请注意,索引字符串在序列类型中有点异常(exception)。 'abc'[0]给你一个str长度为一的对象; str始终是唯一包含自己类型元素的序列类型。

这与其他语言处理字符串数据的方式相呼应;在 C 中 unsigned char type也是 0-255 范围内的有效整数。许多 C 编译器默认为 unsigned如果您使用不合格的char类型,文本被建模为 char[]数组。

关于python - 为什么我在索引字节时会得到一个 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28249597/

相关文章:

python 计算 c 驱动器大小时访问被拒绝

python - 使用 Selenium 和 Python 禁用 Shockwave Flash 插件

javascript - 将表示为 numpy 数组的音频数据从 python 发送到 Javascript

python - 3 用 Numpy 输入逻辑或 where

python - _tkinter 模块未找到

python - 使用python中的plotly方法在y轴刻度中添加货币符号

python - pandas read_csv 每隔一列都有索引

Python/pip,如何从 github 安装特定版本的 git 存储库(正确的 url 是什么)?

python - 使用 pandas 将数据帧从长转换为宽 - 单行输出

python - 为什么我使用pystray时无法关闭?