Latest Code Tutorials

How to Convert Python String to Hex

Hex strings have a “0x” prefix. In Python, if you have a “0x” prefix and a valid string, use the int(string, 0)  method to get the integer. The 0 is provided to tell the function to interpret the base from prefix.

Python String to Hex

To convert Python String to hex, use the inbuilt hex() method. The hex() is a built-in method that converts the integer to a corresponding hexadecimal string. For example, use the int(x, base) function with 16 to convert a string to an integer.

Syntax of hex()



The hex() method takes one required argument n: integer number.

Return Value

The hex() method converts an integer to a corresponding hexadecimal number in the string form and returns it. The returned hexadecimal string starts with the prefix 0x, indicating it’s in the hexadecimal format.

Example of converting a string to hex

hex_string = "0xFF"

an_integer = int(hex_string, 16)

hex_value = hex(an_integer)



You can see from the output that the returned string is hexadecimal because it starts with 0xff.

Python hex() with object

We can also convert a Python object into a hash value using the hex() method. Create a custom class and define __index__() function to use the hex() function with it.

class Ditto:
    no = 0

    def __index__(self):
        print('__index__ function called')

dt = Ditto() = 19



__index__ function called

Hexadecimal representation of a float

Use float.index() method to convert float to hex.

number = 0.0
print(number, "in hex =", float.hex(number))

number = 19.5
print(number, "in hex =", float.hex(number))


0.0 in hex = 0x0.0p+0
19.5 in hex = 0x1.3800000000000p+4

Errors and Exceptions to convert string to hex.

The hex() function throws a TypeError when anything other than integer type constants is passed as parameters.

hex_string = "0xFF"

hex_value = hex(hex_string)


TypeError: 'str' object cannot be interpreted as an integer

You can see that the hex() function always expects an integer, but it got a string, which is why it throws an error. The hex() method is used in all the standard conversions, like converting hexadecimal to decimal, hexadecimal to octal, and hexadecimal to binary.


If you want to convert a hex string (ex: 0xAD4) to a hex number, use the hex() function.

First, use the int() function with the second parameter 16 to convert a hex string to an integer. Then, use the hex() function to convert it to a hexadecimal number.

That’s it for this article.

See also

Python oct()

Python format

Python f-strings

Leave A Reply

Your email address will not be published.

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