What are these symbols in 'bytes' type?


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


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)

Or, using hashlib module:

>>> import hashlib
>>> hashlib.sha256('abc'.encode()).digest()

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

>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 ReplyCancel reply