Saturday, September 26, 2020

Why does Python 3 not print out the hexadecimal values of bytes ?

I was playing with bytes in Python. Here is what I observe,

>>> print(bytes([192,168,1,101]))
b'\xc0\xa8\x01e'
>>>

But I was expect to see

b'\xc0\xa8\x01\x65`
This is mysterious to me also because I observe
>>> for b in b'\xc0\xa8\x01\x65':
...  print(b)
...
192
168
1
101
>>>

After a little bit digging, I became to understand that Python prints out the byte's ASCII character if it is printable; otherwise, it's hexadecimal value. In the ASCII table, we have


Oct   Dec   Hex   Char
...
142   98    62    b
144   100   64    d
145   101   65    e
146   102   66    f
...

To confirm this hypothesis, I did the following test,


>>> print(bytes([99,100,101,102]))
b'cdef'
>>> print(b'\x63\x64\x65\x66')
b'cdef'
>>>

I guess I solved the mystery.

2 comments: