Python hex() Function

The hex() function in Python is used when we need to convert any value to its equivalent hexadecimal value. For example:

print(hex(10))
print(hex(15))
print(hex(123))
print(hex(1234543))

The output will be:

0xa
0xf
0x7b
0x12d66f

Note - The prefix 0x indicates that, after value is hexadecimal value. Therefore, (10)10 = (a)16, (15)10 = (f)16, (123)10 = (7b)16, and (1234543)10 = (12d66f)16.

Python hex() Function Syntax

The syntax of hex() function in Python, is:

hex(val)

where val refers to a value or number of integer type.

Python hex() Function Example

Here is an example of hex() function in Python. This program receives a number from user at run-time of the program, to find and print the equivalent hexadecimal value using hex() function:

print("Enter a Number: ", end="")
num = int(input())
print("\nEquivalent Hexadecimal =", hex(num))

The snapshot given below shows the sample run of above program, with user input 13204

python hex function

Remove 0x Prefix from Returned Hexadecimal using hex() Function

To remove 0x prefix from the returned hexadecimal equivalent of a number using hex() function, use the following program. This program sliced the value from second index.

print("Enter a Number: ", end="")
num = int(input())

h = hex(num)[2:]
print("\nEquivalent Hexadecimal =", h)

Now the output with same user input as of previous sample run, would be:

python hex function example

Python Online Test


« Previous Function Next Function »



Like/Share Us on Facebook 😋