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 ahexstring.
Note: The returned
hexstring always starts with the prefix0x.
Code
The following code shows how to use the hex() function in Python:
# create an integer variable numnum = 45# assign the hex value to the variable hex_numhex_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
numto thehex()function. Then, we assign the result to a new variable,hex_num. -
Line 5: The result is displayed.