18

I'm thinking binascii is the module I'm looking for, but I can't quite seem to get the exact results for which I am looking.

Here's what I want to do. I want to convert:

>>> s = '356a192b7913b04c54574d18c28d46e6395428ab'
>>> print len(s)
40

to

>>> hs = '\x35\x6a\x19\x2b\x79\x13\xb0\x4c\x54\x57\x4d\x18\xc2\x8d\x46\xe6\x39\x54\x28\xab'
>>> print len(hs)
20

Any Pythonistas know of a cool (or, frankly, functional) way to do this?

2 Answers 2

24

In all versions of Python, you can use the function binascii.a2b_hex() (also known as binascii.unhexlify()):

>>> import binascii
>>> s = '356a192b7913b04c54574d18c28d46e6395428ab'
>>> binascii.a2b_hex(s)
'5j\x19+y\x13\xb0LTWM\x18\xc2\x8dF\xe69T(\xab'

In Python 3.x, you can use bytes.fromhex(s).

In Python 2.x, you can use the hex str-to-str codec:

>>> s.decode("hex")
'5j\x19+y\x13\xb0LTWM\x18\xc2\x8dF\xe69T(\xab'

The codec internally calls binascii.a2b_hex().

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

7 Comments

Yep, that's exactly what I was looking for, and it was in the string class waiting for me. Thanks, Sven!
You can also do s.decode("hex").upper() to get uppercase if that is important.
would you mind providing a Python 3.x version since this is the accepted answer (and will likely be so forevers)
@Marc The answer actually already included the Python 3 version without explicitly stating so – now made explicit.
Now you can do bytes.fromhex('356a192b7913b04c54574d18c28d46e6395428ab')
|
4

With binascii module:

>>> from binascii import unhexlify
>>> s = '356a192b7913b04c54574d18c28d46e6395428ab'
>>> unhexlify(s)
'5j\x19+y\x13\xb0LTWM\x18\xc2\x8dF\xe69T(\xab'

1 Comment

unhexlify() is only another name for a2b_hex() binascii Documentation

Your Answer

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