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

ParameterDescription
x An integer.

Return value

A string such as '0xff'.

Examples

To hex and backTry it yourself
print(hex(255), hex(16), hex(-42))
print(int("ff", 16), int("0xff", 0))

Output

0xff 0x10 -0x2a
255 255
A colour code without the 0x prefixTry it yourself
r, g, b = 15, 118, 110
print(f"#{r:02x}{g:02x}{b:02x}")

Output

#0f766e

Version history

VersionChange
Python 3.0Added