在尝试修剪前后括号 - [ 和 ] - 我遇到了一些意想不到的事情。在 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, whileb[0:1]
will be a bytes object of length 1.
关于Python字节串子串切片返回不同的表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53906442/