Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Built-in Functions

Python hex() function

Reference for Python hex(): convert an integer to a lowercase hexadecimal string with a 0x prefix, handle negatives, and format or parse hex values.

The hex() function converts an integer to a string of its value in base 16. The result is lowercase and always starts with the prefix 0x, which makes it a valid Python integer literal.

Hexadecimal is common for colors, memory addresses, byte values and bit masks. Use hex() when you want the prefix; use format() or an f-string when you need padding, uppercase letters or no prefix.

Python
print(hex(255))    # 0xff
print(hex(-26))    # -0x1a

Try it

Python Converting and parsing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Padding and uppercase with formatting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
hex(x)
Name Description
x An int, or any object that defines __index__() returning an integer.

Return value: a str such as '0x1f'. Negative numbers get a leading minus sign: '-0x1f'.

Raises: TypeError if x is not an integer, for example hex(3.5) or hex("10").

Usage notes

  • Always lowercase with 0x. For uppercase digits call .upper() on the digits only, or use the X format code: f"{255:X}" gives FF.
  • Padding needs format(). hex() does not pad. f"{n:04x}" pads to four digits; f"{n:#06x}" keeps the prefix and makes the whole string six characters wide.
  • Negative numbers are shown with a sign, not as two's complement. To see the byte pattern of a negative value, mask it first: hex(-1 & 0xFF) gives '0xff'.
  • Floats are rejected. Use float.hex() for the hexadecimal form of a float (see float methods).
  • Reverse conversion. int("ff", 16) and int("0xff", 16) both parse hex text; base 0 reads the prefix to pick the base.
  • Bytes have their own method. bytes.hex() turns raw bytes into a two-digits-per-byte string (see bytes methods).
  • Other bases: bin() and oct() work the same way for base 2 and base 8.