Reading bytes using python 3.10

Question:

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'x00x01x00x02x00x00x00x03'
>>> test[0]
'x00'
>>> test[1]
'x01'
>>> 

Python 3.10 (converting output to integers).

>>> test = b'x00x01x00x02x00x00x00x03'
>>> 
>>> test[0]
0
>>> test[1]
1
>>> 
Asked By: Sitaram Pamarthi

||

Answers:

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'x00x01'

Python 2 did not have a bytes type, and in fact the b prefix on a string is ignored. 'x00x01....' 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).

Answered By: sj95126
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.