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



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

a = 102.18



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)



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



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

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