How to convert a Python string to Hex format?

Problem

To convert a string data type to an Hexadecimal number format in Python 3.X.

Solution

We have two methods to convert a python string to a Hex value. Using int() function and by importing literal_eval from the ast Python module. In this post, we will learn how we can convert a string to a Hexadecimal number. 

Using the int() function:

Using int(string, base=16) , we can convert the string to an integer with base 16 (Hexadecimal). Once we have the integer, we can use the inbuilt hex() function to convert an integer to a Hexadecimal number. So when we get a string, we will initially convert the string to an integer. We will then convert the integer value to hexadecimal using the function hex(). Let us see it in action.

Code:

def get_hex(value):
    convert_string = int(value, base=16)
    convert_hex = hex(convert_string)
    return convert_hex, convert_string
userstring = "0XABC"
convert_hex, convert_string = get_hex(userstring)
print("String to Integer:",convert_string)
print("Integer to Hex:",convert_hex)

Output:

String to Integer: 2748
Integer to Hex: 0xabc

Using ast.literal_eval() function:

Using the literal_eval from the ast library, we can easily get the string and convert it to an integer. Then we can use the hex() function to get the Hexadecimal value. All we have to do is that we will need to import the literal_eval function from ast. Let us look at an example.

Code:

from ast import literal_eval
def get_hex(value):
    convert_string = literal_eval(value)
    convert_hex = hex(convert_string)
    return convert_hex, convert_string
userstring = "0xabc"
convert_hex, convert_string = get_hex(userstring)
print("String to Integer:",convert_string)
print("Integer to Hex:",convert_hex)

Output:

String to Integer: 2748
Integer to Hex: 0xabc