jwal
jwal

Reputation: 660

Python byte-string substring slices return different representations

In trying to prune a preceding and trailing bracket - [ and ] - I encountered something unexpected. In the python 3.7 interpreter:

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

This feels to me like an inconsistency. I am new to Python, so, am I interpreting this correctly, is this odd?

Upvotes: 3

Views: 1059

Answers (1)

ForceBru
ForceBru

Reputation: 44858

No, this isn't odd:

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

So, an element of bytes is an integer. Obviously, an integer cannot equal a bytes object because it's meaningless (how do you compare b'123' and 12, for example?).

Quote from the 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.

Upvotes: 4

Related Questions