Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing escaping of printable characters when printing bytes in Python 3

I have a bytes object, for instance

test = b'\x83\xf8\x41\x41\x41'

I would like to print this object to stdout, but if I do, Python converts the printable characters in the object to ASCII:

print(test)
b'\x83\xf8AAA'

Is there a way to force Python 3 to print the printable characters (in this instance, three 'A's) as escaped bytes?

That is, so that print(test) outputs

b'\x83\xf8\x41\x41\x41'
like image 800
Carsten Maartmann-Moe Avatar asked Feb 12 '23 05:02

Carsten Maartmann-Moe


1 Answers

No, the repr() output is not configurable; it is a debug tool.

You could use binascii.hexlify() to get a hex representation:

>>> test = b'\x83\xf8\x41\x41\x41'
>>> from binascii import hexlify
>>> test = b'\x83\xf8\x41\x41\x41'
>>> print(hexlify(test))
b'83f8414141'

or you could convert each individual 'byte' value to a hex representation:

>>> print("b'{}'".format(''.join('\\x{:02x}'.format(b) for b in test)))
b'\x83\xf8\x41\x41\x41'

This produces an alternative representation.

like image 168
Martijn Pieters Avatar answered Feb 14 '23 18:02

Martijn Pieters