Python: hex() function

hex() function overview

The Python hex() function converts an integer value to the hexadecimal representation of the number. For the hexadecimal representation of a float value, use the hex() method of floats. The hexadecimal representation is returned as string and starts with the prefix '0x'. To remove the prefix, use slices to return the string starting from index 2: [2:].

hex() function on integer

To find the hexadecimal representation of an integer, use the hex() function as shown below. # find hexadecimal representation of integers print(hex(0)) print(hex(5)) print(hex(25)) print(hex(125)) print(hex(55555)) In this example the integers are converted to hexadecimal representations and then printed. The result is shown below, note that the return values are beginning with the prefix '0x'. 0x0 0x5 0x19 0x7d 0xd903

hex() syntax

The syntax of the hex() function is: hex(integer)

hex() arguments

The hex() function accepts exactly one argument. The arguments has to be an integer value. If more than one or no argument at all is passed to the hex() function a TypeError exception is raised. The TypeError raised if no argument is passed to the hex() function: TypeError: hex() takes exactly one argument (0 given) The TypeError raised if a float value is passed to the hex() function: TypeError: 'float' object cannot be interpreted as an integer

hex() function return values

The hex() function returns the hex representation of the given integer. The hexadecimal value is returned as string with the prefix '0x'.

remove 0x prefix of hex() return value

To remove the prefix 0x of the hex() function return value, use slices as shown below. # remove 0x prefix of hex() return value myHex = hex(25) # print with prefix print(myHex) # print without prefix print(myHex[2:]) In this example, we convert the integer 25 to the hexadecimal representation and assign it to the variable myHex. Then the variable is printed with and without the prefix. To remove the prefix we use slices: [2:] to return the string starting from index 2, which is the third character in the string. The result is shown below, first the string with prefix is printed and then the string without prefix is printed. 0x19 19



Click to jump to section