35

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.

2
  • see this answer: stackoverflow.com/a/2340358/1298523 Commented Oct 16, 2012 at 15:55
  • 3
    I would argue against closing this as a dupe. This question is specifically about Python 3.2 where the hex codec is officially back (but harder to find). The linked question is about Python 3.1. Commented Oct 16, 2012 at 16:07

5 Answers 5

31

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".

Sign up to request clarification or add additional context in comments.

3 Comments

Don't you mean codecs.encode(b'\x12', 'hex_codec')? With 'hex' I only get LookupError: unknown encoding: hex
The docs say hex is an alias in 3.2, but my 3.2.3 installation had the same error.
While I can't find a reference to a bugfix, it looks like hex is working again as of 3.4.
14

Yet another way using binascii.hexlify():

>>> import binascii
>>> binascii.hexlify(b'\x12\x34\x56\x78')
b'12345678'

2 Comments

So you took a glance at the so-called dupe, yes? :)
No, that's the way I usually do it :)
11

Using base64.b16encode():

>>> import base64
>>> base64.b16encode(b'\x12\x34\x56\x78')
b'12345678'

Comments

9

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'

2 Comments

str(x,'ascii') is better spelt x.decode('ascii')
binascii also seems faster, for anyone who cares.
3

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.