Open In App

Convert Hex To String Without 0X in Python

Last Updated : 01 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Hexadecimal representation is a common format for expressing binary data in a human-readable form. In Python, converting hexadecimal values to strings is a frequent task, and developers often seek efficient and clean approaches. In this article, we’ll explore three different methods to convert hex to string without the ‘0x’ prefix in Python.

Convert Hex To String Without 0X In Python

Below, are the ways to Convert Hex To String Without 0X In Python.

Convert Hex To String Using List Comprehension

In this example, as below approach involves using list comprehension to iterate through the hex string, converting each pair of characters into integers and then joining them as a string.

Python3




# Example hex values
hex_values = "5072617468616d20536168616e69" 
result_string = ''.join([chr(int(hex_values[i:i+2], 16)) for i in range(0, len(hex_values), 2)])
 
print(result_string)
print(type(result_string))


Output

Pratham Sahani
<class 'str'>


Convert Hex To String Using bytes.fromhex

In thsi example, as below bytes.fromhex method in Python is designed to create a bytes object from a hexadecimal string. Combining it with the decode method allows us to obtain a string without the ‘0x’ prefix.

Python3




# Example hex values
hex_values = "4765656b73666f724765656b73" 
byte_values = bytes.fromhex(hex_values)
result_string = byte_values.decode('utf-8')
 
print(result_string)
print(type(result_string))


Output

GeeksforGeeks
<class 'str'>


Convert Hex To String Without 0X Using codecs.decode

In this example, In below code codecs module in Python provides a versatile way to handle encodings. By using codecs.decode, we can directly convert the hex string to a Unicode string without the ‘0x’ prefix.

Python3




import codecs
 
# Example hex values
hex_values = "48656c6c6f20576f726c64" 
result_string = codecs.decode(hex_values, 'hex').decode('utf-8')
 
print(result_string)
print(type(result_string))


Output

Hello World
<class 'str'>


Conclusion

In this article, we explored three different approaches to convert hex to string without the ‘0x’ prefix in Python. The bytes.fromhex and codecs.decode methods offer a straightforward and readable solution, leveraging built-in functionalities. On the other hand, the list comprehension and int conversion approach provides a concise alternative for those who prefer a more explicit conversion process.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads