Python hex() Method

The hex() method converts an integer number to a lowercase hexadecimal string prefixed with "0x". If the specified value is not an int object, it has to define an __index__() method that returns an integer.

hex() Syntax:



x: An integer number.

Return type:

Returns a hexadecimal string prefixed with '0x'.

The following demonstrates the hex() method.

Example: hex()
print("Hexadecimal of 10 is: ", hex(10))
print("Hexadecimal of -5 is: ", hex(-5))

val = hex(100) # returns string type
Hexadecimal of 10 is:  0xa
Hexadecimal of -5 is:  '-0x5'
<class 'str'>

Use the float.hex() function to convert a float to hexadecimal, as shown below.

Example: hex()
# hex(10.1) # raise an error
print("Hexadecimal of 3.9 is: ", float.hex(10.1)) # valid

Use the int() function to convert hexadecimal to an integer.

Want to check how much you know Python?