Search code examples
pythonencodingpython-3.xhex

How to use the 'hex' encoding in Python 3.2 or higher?


In Python 2, to get a string representation of the hexadecimal digits in a string, you could do

>>> '\x12\x34\x56\x78'.encode('hex')
'12345678'

In Python 3, that doesn't work anymore (tested on Python 3.2 and 3.3):

>>> '\x12\x34\x56\x78'.encode('hex')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
LookupError: unknown encoding: hex

There is at least one answer here on SO that mentions that the hex codec has been removed in Python 3. But then, according to the docs, it was reintroduced in Python 3.2, as a "bytes-to-bytes mapping".

However, I don't know how to get these "bytes-to-bytes mappings" to work:

>>> b'\x12'.encode('hex')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'bytes' object has no attribute 'encode'

And the docs don't mention that either (at least not where I looked). I must be missing something simple, but I can't see what it is.


Solution

  • From python 3.5 you can simply use .hex():

    >>> b'\x12\x34\x56\x78'.hex()
    '12345678'