Here are three ways to convert string to hexadecimal in Python:
- Using hex()
- Using encode()
- Using literal_eval()
Method 1: Using hex()
The hex() method requires an integer as its parameter. Therefore, we must first convert the string into an integer before passing it to the hex().
Visual Representation
string = "0xFF"
print("The data type of string is", type(string))
print("After converting string to hexadecimal :")
int_value = int(string, 16)
hex_value = hex(int_value)
print(hex_value)
print("The data type of hex_value is", type(hex_value))
Output
0xff
The data type of hex_value is <class 'str'>
Method 2: Using encode()
We can use the built-in encode() method to first convert the string to bytes, and then the hex() method to convert these bytes to a hexadecimal string.
Visual Representation
string_value = "AppDividend"
print("The data type of string_value is", type(string_value))
print("After converting string to hexadecimal")
hex_value = string_value.encode().hex() #using UTF-8 encoding by default
print(hex_value)
print("The data type of hex_value is", type(hex_value))
Output
The data type of string_value is <class 'str'>
After converting string to hexadecimal
4170704469766964656e64
The data type of hex_value is <class 'str'>
Method 3: Using ast.literal_eval ()
from ast import literal_eval
str = "0xFFF"
# Convert the str to an integer
con_val = literal_eval(str)
# Print the value
print(con_val)
# Pass the converted value to the hex() method
hex_value = hex(con_val)
# Print the hex value
print(hex_value)
# Check the type of the hex value
print("The data type of hex is", type(hex_value))
Output
4095
0xfff
Type: <class 'str'>
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.