Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

hex()

Formats an integer as a hexadecimal string with a base prefix.

Version: Python 3.14; repository image, production runtime not attested

Syntax

hex(integer, /)

Formats an integer as a hexadecimal string with a base prefix.

A negative argument keeps a minus sign before the prefix. Width and padding require a separate formatting specification.

Two hexadecimal digits ff stand for 15×16+15, so 255 produces 0xff. Negative sixteen is -0x10, with the sign before the prefix. Uppercase digits and minimum width require a format specification. An integer-like object can provide __index__.

assert hex(255) == "0xff" and hex(-16) == "-0x10"
assert format(15, "04X") == "000F" and format(0x12345, "04X") == "12345"

Examples

print(hex(255))
print(hex(-16))

Result

0xff
-0x10

Two hexadecimal digits ff stand for 15×16+15, so 255 produces 0xff. Negative sixteen is -0x10, with the sign before the prefix. Uppercase digits and minimum width require a format specification. An integer-like object can provide `__index__`.

Sources