String to Hex in Python

Hexadecimal values have a base of 16. In Python, hexadecimal strings are prefixed with 0x.

The hex() function is used to convert a decimal integer to its respective hexadecimal number. For example,

a = 102
print(hex(a))

Output:

0x66

We can also convert float values to hexadecimal using the hex() function with the float() function. The following code implements this.

a = 102.18
print(float.hex(a))

Output:

0x1.98b851eb851ecp+6

We cannot convert a string using this function. So if we have a situation where we have a hexadecimal string and want to convert it into the hexadecimal number, we cannot do it directly. For such cases, we have to convert this string to the required decimal value using the int() function and then convert it to the hexadecimal number using the hex() function discussed earlier.

The following code shows this.

hex_s = '0xEFA'
a = int(hex_s,16)
hex_n = hex(a)
print(hex_n)

Output:

0xefa

Characters in the string do not have any corresponding hexadecimal value. However, if we convert a string to a bytes type object, using the encode() function, we can convert it to its hexadecimal value using the hex() function.

For example,

s= 'Sample String'.encode('utf-8')
print(s.hex())

Output:

53616d706c6520537472696e67

In the above code, we encode the string in the utf-8 type and convert it into byte types.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python String

  • Check a String Is Empty in a Pythonic Way
  • Convert String to Bytes in Python
  • Related Article - Python Hex

  • Encrypt a Python String
  • Strip Punctuation From a String in Python