Python 3 reference · Built-in Functions
Python hex() Function
Convert an integer to a lowercase hexadecimal string prefixed with 0x, such as hex(255) giving '0xff'.
Python 3 Since 3.0
Syntax
hex(x)
Parameters
| Parameter | Description |
|---|---|
x |
An integer. |
Return value
A string such as '0xff'.
Examples
print(hex(255), hex(16), hex(-42))
print(int("ff", 16), int("0xff", 0))
Output
0xff 0x10 -0x2a 255 255
r, g, b = 15, 118, 110
print(f"#{r:02x}{g:02x}{b:02x}")
Output
#0f766e
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
bin()· Convert an integer to a binary string prefixed with 0b, such as bin(5) giving '0b101'. Negative numbers get a minus sign.oct()· Convert an integer to an octal string prefixed with 0o, such as oct(8) giving '0o10'. Often used for file permissions.int()· Convert a number or string to an integer. Floats are truncated toward zero, and strings can be in any base from 2 to 36.format()· Format a single value with a format spec, such as format(3.14159, '.2f') giving '3.14'. The same mini-language as f-strings.- Python Numbers · tutorial