Print string as python hex literal

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 like:

In [71]: x
Out[71]: '\x01ABC'

This fixes the pain, because the lines I print are not like literals in my code. How to print strings as hexadecimal literals?

+4
source share
3 answers

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

Since it .encode('hex')is misused encodeand 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
+2
source

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
0
source

~ literal (.. , ), - :

>>> x = '\x1\41\42\43'
>>> print "'" + ''.join(["\\"+ hex(ord(c))[-2:] for c in x]) + "'"
'\x1\41\42\43'
0

Source: https://habr.com/ru/post/1528211/


All Articles