What is the hex() function in Python?

The hex() function

In Python, the hex() function gets the hexadecimal string of a given integer value.

Syntax

hex(number)

Parameter

  • number: This represents the integer value that needs to be converted to a hex string.

Note: The returned hex string always starts with the prefix 0x.

Code

The following code shows how to use the hex() function in Python:

# create an integer variable num
num = 45
# assign the hex value to the variable hex_num
hex_num = hex(num)
print(f"The hexadecimal string for {num}: {hex_num}")

Explanation

  • Line 2: We create a variable named num.

  • Line 4: We pass the value of num to the hex() function. Then, we assign the result to a new variable, hex_num.

  • Line 5: The result is displayed.

Free Resources