Convert Hex to String in Python
Hexadecimal (base-16) is a compact way of representing binary data using digits 0-9 and letters A-F. It's commonly used in encoding, networking, cryptography and low-level programming. In Python, converting hex to string is straightforward and useful for processing encoded data.
Using List Comprehension
This method splits the hex string into pairs of characters, converts each to an integer, then to a character (using ASCII values ) and then joins the result to form a string.
hex_str = "5072616a6a77616c"
res = ''.join([chr(int(hex_str[i:i+2], 16)) for i in range(0, len(hex_str), 2)])
print(res)
print(type(res))
Output
Prajjwal <class 'str'>
Explanation:
- The hex string is split into 2-character chunks.
- Each chunk is converted from base-16 to an integer using int(..., 16).
- chr() converts each integer to its corresponding character.
- join() merges all characters into a single string.
Other Methods to Convert Hex to String:
- Using List Comprehension
- Using codecs.decode()
- Using bytes.fromhex()
Let's discuss how to use these methods with examples:
Using codecs.decode()
The codecs module can directly decode a hex string into bytes, which can then be converted to a string.
import codecs
hex_str = "507974686f6e"
res = codecs.decode(hex_str, 'hex').decode('utf-8')
print(res)
print(type(res))
Output
Python <class 'str'>
Explanation:
- codecs.decode(hex_str, 'hex') converts the hex string into bytes.
- .decode('utf-8') converts those bytes into a readable string.
Using bytes.fromhex()
This built-in method converts a hex string into bytes. Use .decode() to convert it to a UTF-8 string.
hex_str = "4765656b73666f724765656b73"
res = bytes.fromhex(hex_str).decode('utf-8')
print(res)
print(type(res))
Output
GeeksforGeeks <class 'str'>
Explanation:
- bytes.fromhex() converts the hex string into a bytes object.
- .decode('utf-8') turns those bytes into a standard string.
Also reads: Python, hexadecimal, list comprehension, codecs.decode(), bytes.fromhex().