How to Convert String to Hex in Python [3 Ways]

Here are three ways to convert string to hexadecimal in Python:

  1. Using hex()
  2. Using encode()
  3. 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

Visualization of Using hex()

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

Visual Representation of Using encode() Method

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

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.