Python字节串子串切片返回不同的表示

标签 python arrays

在尝试修剪前后括号 - [ 和 ] - 我遇到了一些意想不到的事情。在 python 3.7 解释器中:

>>> string = [b'0123456789']
>>> string[0][:5]
b'01234'
>>> string[0][0]
48
>>> string[0][:5] == b'01234'
True
>>> string[0][0] == b'0'
False

这对我来说是一种矛盾。我是 Python 的新手,所以,我是否正确解释了这一点,这很奇怪吗?

最佳答案

不,这并不奇怪:

>>> type(b'0')
<class 'bytes'>
>>> type(b'0'[0])
<class 'int'>

因此,bytes元素 是一个整数。显然,整数不能等于 bytes 对象,因为它没有意义(例如,如何比较 b'123'12?)。

引自docs :

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.

关于Python字节串子串切片返回不同的表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53906442/

相关文章:

python - 从边缘图像中提取成分并存储以进行进一步处理

Python BeautifulSoup 城市抓取并发症

python - 在 Python GUI 加载时显示图像

javascript - javascript中对象的递归合并

javascript - 如何从数组中获取不匹配的元素?

c - 如何将字符串存储在数组中?

java - 在每个循环中,我想在最后一次迭代中跳过 ", "

python - 如何在Python中将数字减法字符串转换为整数?

ios - Swift 将 Int[] 转换为 Int 变量

python - 命令 onkey() 出错