How to Convert a String to Hex in Python

To convert a string into a hexadecimal representation, first convert it into an integer using the Python int() function using 16 as the base, then into a hex using the Python hex() function.

 

To demonstrate this, let's create a hex string, convert it into a base-10 integer, then turn it back into a hexadecimal representation.

 

hex_str = '0x2e6'

base_10 = int(hex_str, 16)

hex_new = hex(base_10)

print(hex_new)
0x2e6
number string