I have a hex string like:
data = \"437c2123\"
I want to convert this string to a sequence of characters according to the ASCII table. The
The ord function converts characters to numerical values and the chr function does the inverse. So to convert 97 to "a", do ord(97)
Since Python 2.6 you can use simple:
data_con = bytes.fromhex(data)
In [17]: data = "437c2123"
In [18]: ''.join(chr(int(data[i:i+2], 16)) for i in range(0, len(data), 2))
Out[18]: 'C|!#'
Here:
for i in range(0, len(data), 2) iterates over every second position in data: 0, 2, 4 etc.data[i:i+2] looks at every pair of hex digits '43', '7c', etc.chr(int(..., 16)) converts the pair of hex digits into the corresponding character.''.join(...) merges the characters into a single string.In Python2
>>> "437c2123".decode('hex')
'C|!#'
In Python3 (also works in Python2, for <2.6 you can't have the b prefixing the string)
>>> import binascii
>>> binascii.unhexlify(b"437c2123")
b'C|!#'