The Python hex() function
hex() is a built-in Python function that converts an integer to a hexadecimal string.
Hexadecimal is a commonly used number representation in computing, with digits 0-9 and letters a-f representing 10-15.hex() The function is often used in debugging, color codes, memory addresses, and similar scenarios.
Word meaning: hex is short for hexadecimal.
Basic syntax and parameters
Syntax format
hex(x)
Parameter Description
- Parameter x:
- Type: integer
- Description: the integer to convert to hexadecimal.
Function description
- Return Value: returns a hexadecimal string starting with "0x".
Example
Example 1: basic usage
Example
Basic conversions
(
hex
(
10
)
)
Output: 0xa
(
hex
(
255
)
)
Output: 0xff
(
hex
(
256
)
)
Output: 0x100
Negative numbers (a minus sign is shown)
(
hex
(
10
)
)
Output: -0xa
(
hex
(
255
)
)
Output: -0xff
zero
(
hex
(
0
)
)
Output: 0x0
Large numbers
(
hex
(
16
)
)
Output: 0x10
(
hex
(
255
)
)
Output: 0xff
(
hex
(
4096
)
)
Output: 0x1000
Expected output:
0xa
0xff
0x100
-0xa
-0xff
0x0
0x10
0xff
0x1000
Code analysis:
- The returned string starts with "0x", indicating hexadecimal.
- Letters are lowercase by default (a-f).
- Negative numbers show a minus sign.
Example 2: practical applications
Example
Color code conversion
r
,
g
,
b
=
255
,
128
,
0
color
=
f
"#{hex(r)[2:]:0>2}{hex(g)[2:]:0>2}{hex(b)[2:]:0>2}"
(
color
)
Output: #ff8000
Using formatting
(
f
"{10:#x}"
)
Output: 0xa
(
f
"{255:#x}"
)
Output: 0xff
(
f
"{255:x}"
)
Output: ff
Remove the 0x prefix
s
=
hex
(
255
)
(
s
[
2
:
]
)
Output: ff
(
s.
replace
(
"0x"
,
""
)
)
Output: ff
Expected output:
#ff8000
0xa
0xff
ff
ff
ff
Hexadecimal is often used in color codes, debug output, and similar scenarios.
Python3 built-in function