["python","arrays"]
How to convert hexadecimal string to bytes in Python?

I have a long Hex string that represents a series of values of different types. I need to convert this Hex String into bytes or bytearray so that I can extract each value from the raw data. How can I do this? For example, the string "ab" should convert to the bytes b"\xab" or equivalent byte array. Longer example: >>> # what to use in place of `convert` here? >>> convert("8e71c61de6a2321336184f813379ec6bf4a3fb79e63cd12b") b'\x8eq\xc6\x1d\xe6\xa22\x136\x18O\x813y\xeck\xf4\xa3\xfby\xe6<\xd1+'
Suppose your hex string is something like >>> hex_string = "deadbeef" Convert it to a bytearray (Python 3 and 2.7): >>> bytearray.fromhex(hex_string) bytearray(b'\xde\xad\xbe\xef') Convert it to a bytes object (Python 3): >>> bytes.fromhex(hex_string) b'\xde\xad\xbe\xef' Note that bytes is an immutable version of bytearray. Convert it to a string (Python ≤ 2.7): >>> hex_data = hex_string.decode("hex") >>> hex_data "\xde\xad\xbe\xef"