Horje
Convert Hex to String in Python

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

Convert Hex To String In Python

Below, are the ways to Convert Hex To String in Python:

Convert Hex To String Using List Comprehension

In this example, the 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 = "53686976616e6720546f6d6172" 
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

Shivang Tomar
<class 'str'>


Convert Hex To String Using codecs.decode

In this example, the 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 string.

Python3

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

Output

Python
<class 'str'>


Convert Hex To String Using bytes.fromhex()

In thsi example, we are using bytes.fromhex() method in Python that is designed to create a bytes object from a hexadecimal string. Combining it with the decode method allows us to obtain a string.

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'>





Reffered: https://www.geeksforgeeks.org


Geeks Premier League

Related
Python Naming Conventions Python Naming Conventions
Create a New Text File in Python Create a New Text File in Python
Gps Tracker Using Python Gps Tracker Using Python
Resolve Stopiteration Error in Python Resolve Stopiteration Error in Python
Exploitation of Children - Fundamental Rights Exploitation of Children - Fundamental Rights

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13