Print string as hex literal python

escaping, python, string

Solution

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

Problem

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?

Original source