Reputation: 24547
I have a lot of pre-existing code that treats byte arrays as strings, i.e.
In [70]: x = '\x01\x41\x42\x43'
Which python always prints as:
In [71]: x
Out[71]: '\x01ABC'
This makes debugging a pain, since the strings I print don't look like the literals in my code. How to I print strings as hex literals?
Upvotes: 5
Views: 8202
Reputation: 981
In python3, I generally write a small function to do this.
def print_hex_string(data):
result = ''
for c in data:
result += f'\\x{c:02x}'
print("b'" + result + "'")
x = b'\x01\x41\x42\x43'
print(x)
# b'\x01ABC'
print_hex_string(x)
# b'\x01\x41\x42\x43'
binascii
is not needed since you can just do x.hex()
for the same result.
print(x.hex())
# 01414243
oneliner:
x = b'\x01\x41\x42\x43'
print(''.join([f'\\x{c:02x}' for c in x]))
# \x01\x41\x42\x43
Upvotes: 0
Reputation: 24547
To actually print out the string ~literal (i.e. the thing you can cut and paste back into your code to get the same object) requires something like:
>>> x = '\x1\41\42\43'
>>> print "'" + ''.join(["\\"+ hex(ord(c))[-2:] for c in x]) + "'"
'\x1\41\42\43'
Upvotes: 0
Reputation: 176780
For a cross-version compatible solution, use binascii.hexlify
:
>>> import binascii
>>> x = '\x01\x41\x42\x43'
>>> print x
ABC
>>> repr(x)
"'\\x01ABC'"
>>> print binascii.hexlify(x)
01414243
As .encode('hex')
is a misuse of encode
and has been removed in Python 3:
Python 3.3.1
Type "help", "copyright", "credits" or "license" for more information.
>>> '\x01\x41\x42\x43'.encode('hex')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
LookupError: unknown encoding: hex
Upvotes: 2
Reputation: 35109
You can try something like this:
>>> x = '\x01\x41\x42\x43'
>>> x.encode('hex')
'01414243'
or
>>> x = r'\x01\x41\x42\x43'
>>> x
'\\x01\\x41\\x42\\x43'
or
>>> x = '\x01\x41\x42\x43'
>>> print " ".join(hex(ord(n)) for n in x)
0x1 0x41 0x42 0x43
Upvotes: 1