Write a hex string as binary data in Python

You're looking for binascii.

binascii.unhexlify(hexstr)
Return the binary data represented by the hexadecimal string hexstr.
This function is the inverse of b2a_hex(). hexstr must contain
an even number of hexadecimal digits (which can be upper or lower
case), otherwise a TypeError is raised.

import binascii
hexstr = 'FF0000FF'
binstr = binascii.unhexlify(hexstr)

You could use bytes's hex and fromhex like this:

>>> ss = '7e7e303035f8350d013d0a'
>>> bytes.fromhex(ss)
b'~~005\xf85\r\x01=\n'
>>> bb = bytes.fromhex(ss)
>>> bytes.hex(bb)
'7e7e303035f8350d013d0a'

Tags:

Python

Hex