Home > database >  convert byte to string represented with backslahes in python
convert byte to string represented with backslahes in python

Time:10-01

I have a python byte object like

a = b'1'

I want to convert to string like

"\\x31"

is there any easy way to do this?

Ultimately I have a byte object like

my_obj = b'\x00$\x00\x00\x001.1.0.00\x00\x00\x00\x00\x00\x00\x00\x001.1.0.21152\x00\x00'

and I want it to have a string with all chars backscaped.

CodePudding user response:

a = b'12'
s = "".join(f"\\x{abyte:02x}" for abyte in a)
# something like "\\x33\\x34"

I guess ... i still think you dont actually want to do this ...

if its just for readability then this is a good answer

import binascii
print(binascii.hexlify(a," ")) # something like "33 34"
  • Related