Show hex value for all bytes, even when ASCII characters are present

There is no specific means of requiring any particular formatting (like \x) for a byte string. If you really need specific formatting, you could use something like the .hex() solution from this question, but wrap it with other code to insert the formatting you need. Another useful tool is the hex builtin function. For instance, if you want \x:

>>> x = bytes([67, 128])
>>> print(''.join(r'\x'+hex(letter)[2:] for letter in x))
\x43\x80

If you just need to be able to visually distinguish the bytes, using hex by itself may work for you (it uses 0x instead of \x):

>>> print(''.join(hex(letter) for letter in x))
0x430x80

There is not a way to make this the default behavior for byte strings. Whatever you do, you're going to have to write code that specifies the display format you want; you can't make Python automatically display printable bytes as \x escapes.


After installing my package all-escapes there will be a new codec available for this usage.

>>> b = bytes([10,67,128])
>>> print(b.decode("all-escapes"))
\x0a\x43\x80

Tags:

Python