3

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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I interpreted [0] as being equal to [0:1]. Interesting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.