Home / Python / Reference / Built-in functions

Python hex() function

Write a whole number in hexadecimal (base 16), as a string starting with 0x.

Syntax

hex(x)

Hexadecimal is used for colours (#FF8800), memory addresses and bytes.

Parameters

xan int

Return value

str

Example

Code

print(hex(255), hex(16))
r, g, b = 46, 111, 242
print(f"#{r:02X}{g:02X}{b:02X}")   # a colour code

Output

0xff 0x10
#2E6FF2

Related

Learn it step by step in the free lesson Values, Variables & Numbers, with exercises that check your answers.