0

When I am reading individual elements from bytes it is returning a integer value rather than returning the hex code. This I am noticing with Python 3 only (tested in v3.10). Any idea how this can adjusted? Below are the code and output from both Python 2.7 (which works fine) and Python 3.10 (which is converting to integers).

Python 2.7 (works fine)

>>> test = b'\x00\x01\x00\x02\x00\x00\x00\x03'
>>> test[0]
'\x00'
>>> test[1]
'\x01'
>>> 

Python 3.10 (converting output to integers).

>>> test = b'\x00\x01\x00\x02\x00\x00\x00\x03'
>>> 
>>> test[0]
0
>>> test[1]
1
>>> 
1
  • As designed. Bytes are data and individual bytes are integers 0-255 Commented Aug 30, 2022 at 1:10

1 Answer 1

2

Python 3 has a bytes type. When you create a binary string with b'...', you create an immutable sequence of bytes. Indexing that sequence returns type int. A slice of a b-string will be in bytes form like this:

>>> test[:2]
b'\x00\x01'

Python 2 did not have a bytes type, and in fact the b prefix on a string is ignored. '\x00\x01....' is just a string of non-representable characters in hex-escape syntax. Indexing and slicing that string returns another string (of one or more characters).

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

1 Comment

To understand Python 2 a little better, slip a \x5a in the middle of the string.

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.