Ethan Shaotran
Ethan Shaotran

Reputation: 31

Why is ByteArray() combining array values? (Python)

>>> bytearray([2,88])
bytearray(b'\x02X')

Why is bytearray() combining them? And why is it turning 88 into ascii (X)? I was expecting two separate values, and 88 to convert to hex (x58)

bytearray(b'\x02,x58)

Upvotes: 1

Views: 113

Answers (1)

fferri
fferri

Reputation: 18950

Because ASCII 88 (capital letter X) is printable, and the behavior of bytes.str() / bytes.repr() is to not encode printable characters.

Just try to print bytearray(range(256)) and you'll see that there is a range of printable characters (from \x20 to \x7e) which do not get displayed as \x##.

Nonetheless, you can input \x58 in a byte sequence, but it will again be displayed as X:

>>> b'\x58'
b'X'

Here's a little trick to print all values encoded to \x## form:

>>> b = bytearray([2,88])
>>> print(''.join('\\x%02x'%x for x in b))
\x02\x58

Upvotes: 1

Related Questions