What are these symbols in 'bytes' type?

So, I have a single byte in bytes format looking something like that:

b'\xFF'

It is quite easy to understand that a single byte is the two symbols(0-F) after ‘\x’

But sometimes the pattern doesn’t match, containing more than two symbols after ‘\x’.

So, for example, if I use secrets.token_bytes() I can get something like that:

>>> import secrets
>>> secrets.token_bytes(32)
b't\xbcJ\xf0'

Or, using hashlib module:

>>> import hashlib
>>> hashlib.sha256('abc'.encode()).digest()
b'\xbax\x16\xbf\x8f\x01\xcf\xeaAA@\xde]\xae"#\xb0\x03a\xa3\x96\x17z\x9c\xb4\x10\xffa\xf2\x00\x15\xad'

So, can someone, please, explain what are those additional symbols purpose and how are they generated?
Thanks!

>Solution :

It’s a quirk of the way Python prints byte strings. If the byte value is one of the printable ASCII characters it will print that character; otherwise it prints the hex escape.

Show bytes(range(0x100)) to see it visually.

To get a string that consistently uses hex escapes, you need to build it yourself.

print(''.join(f'\\x{i:02x}' for i in bytes(range(0x100))))

Leave a Reply