You can use 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 an Error exception is raised.
x.strip() removes the line feed
the [2:] slices off the 0x
the decode() at the end flips from bytes
import binascii x = b'0x31303032\n' x1 = binascii.unhexlify(x.strip()[2:]).decode() print(x1)results:
Output:1002
I should explain a bit: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 an Error exception is raised.
x.strip() removes the line feed
the [2:] slices off the 0x
the decode() at the end flips from bytes