Python hex() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
Built-in

Definition

In Python, hex(x) converts an integer to a hexadecimal (base 16) string with the prefix 0x and lowercase letters: hex(255) returns '0xff'. Each hex digit stands for four bits, so two digits make one byte.

Hex is used for colors (#ffa500), byte dumps, and bit masks. For padding, uppercase, or no prefix, use format() or f-strings; to go back, use int(text, 16).

hex() is a built-in function: it lives in the builtins module, so it is always available without an import.

Syntax

Pass an int; you get lowercase hex text.

python
text = hex(number)      # '0x...'
CallWhat it does
hex(255)Returns '0xff'.
hex(-42)Returns '-0x2a'.
format(255, "02X")Returns 'FF': uppercase, no prefix.
int("ff", 16)Returns 255.

For a whole bytes object, data.hex() is simpler than calling hex() on every byte.

Library declarations
python
hex(x, /)
# x: int, or an object with __index__()

Parameters

ParameterDescription
xRequired. An int or an object that defines __index__().

Return Value

Return ValueDescription
strLowercase hex digits prefixed with 0x (or -0x).

Python Examples

Example 1 — Hex Strings for Several Integers

See where hex switches from digits to letters and how bigger numbers grow.

python
for n in [9, 10, 15, 16, 255, 4096, -42]:
    print(n, hex(n))

How It Works

  1. Letters for 10 to 15. Hex needs 16 digit symbols, so 10 is a and 15 is f.
  2. Carry at 16. 16 is written 10, and 4096 (16 cubed) is 1000.
  3. One byte. 255 is ff, the largest value two hex digits can hold.
  4. Negative. 42 is 2 * 16 + 10, so -42 prints as -0x2a.

Example 2 — Build and Parse HTML Color Codes

Format RGB values as a hex color, uppercase it, pad hex with a prefix, and parse a color back into numbers.

python
def to_hex_color(r, g, b):
    return f"#{r:02x}{g:02x}{b:02x}"


print(to_hex_color(255, 165, 0))
print(to_hex_color(18, 52, 86).upper())
print(hex(255).upper())
print(format(255, "#06x"))

color = "1e90ff"
r, g, b = (int(color[i:i + 2], 16) for i in (0, 2, 4))
print(r, g, b)

How It Works

  1. Two digits per channel. :02x writes each value as two lowercase hex digits: 255, 165, 0 become ff, a5, 00.
  2. Uppercase. 18, 52, 86 are 0x12, 0x34, 0x56; .upper() changes nothing visible here, but hex(255).upper() becomes 0XFF.
  3. Padded with prefix. "#06x" counts 0x in the width of 6, giving 0x00ff.
  4. Parse back. Slicing two characters at a time and calling int(..., 16) turns 1e90ff into 30, 144, 255.

Example 3 — Hex for Bytes and Floats

Dump bytes as hex, rebuild them with bytes.fromhex(), and show the exact value of a float.

python
data = b"Hi!"

print(data.hex())
print([hex(b) for b in data])
print(bytes.fromhex("486921"))
print((0.5).hex())

try:
    hex(2.5)
except TypeError:
    print("hex() needs an int; use float.hex() for floats")

How It Works

  1. Whole bytes object. data.hex() writes two hex digits per byte with no prefixes: H, i, ! are 48, 69, 21.
  2. Byte by byte. Iterating over bytes yields ints, so hex(b) works on each one.
  3. Back to bytes. bytes.fromhex() reverses hex() and prints b'Hi!'.
  4. Floats differ. (0.5).hex() shows mantissa and exponent (1.0 times 2 to the -1); hex(2.5) raises TypeError.

Frequently Asked Questions

Call hex(n), for example hex(255) returns '0xff'. Use format(n, "x") for the digits only.
Use format(n, "X") or f"{n:X}". format(255, "X") returns 'FF'.
Use format(n, "02x") or f"{n:02x}", for example format(5, "02x") is '05'.
Use int("ff", 16). With a prefix, int("0xff", 16) and int("0xff", 0) also work.
Call data.hex(). To go back, use bytes.fromhex(text).

Next: id()

Get an object's identity, unique while it is alive.

id() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

13 people found this page helpful