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'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With