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

Question:

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

>>> 'x12x34x56x78'.encode('hex')
'12345678'

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

>>> 'x12x34x56x78'.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.

Asked By: Tim Pietzcker

||

Answers:

You need to go via the codecs module and the hex_codec codec (or its hex alias if available*):

codecs.encode(b'x12', 'hex_codec')

* From the documentation: “Changed in version 3.4: Restoration of the aliases for the binary transforms”.

Answered By: ecatmur

Using base64.b16encode():

>>> import base64
>>> base64.b16encode(b'x12x34x56x78')
b'12345678'
Answered By: dan04

Yet another way using binascii.hexlify():

>>> import binascii
>>> binascii.hexlify(b'x12x34x56x78')
b'12345678'
Answered By: Mark Tolonen

binascii methods are easier by the way:

>>> import binascii
>>> x=b'test'
>>> x=binascii.hexlify(x)
>>> x
b'74657374'
>>> y=str(x,'ascii')
>>> y
'74657374'
>>> x=binascii.unhexlify(x)
>>> x
b'test'
>>> y=str(x,'ascii')
>>> y
'test'
Answered By: iMagur
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.