Skip to content

hex()

The built-in hex() function converts a given integer into its hexadecimal representation. The output is a string prefixed with 0x:

Language: Python
>>> hex(42)
'0x2a'

hex() Signature

Language: Python Syntax
hex(x)

Arguments

Argument Description
x An integer value or an object defining an .__index__() method that returns an integer.

Return Value

  • Returns a string holding the hexadecimal representation of the input integer, prefixed with 0x.

hex() Examples

With a positive integer as an argument:

Language: Python
>>> hex(255)
'0xff'

With a negative integer as an argument:

Language: Python
>>> hex(-42)
'-0x2a'

With an object of a class with a .__index__() method:

Language: Python
>>> class Number:
...     def __init__(self, value):
...         self.value = value
...     def __index__(self):
...         return self.value
...

>>> number = Number(10)
>>> hex(number)
'0xa'

hex() Common Use Cases

The most common use cases for the hex() function include:

  • Converting integer values to hexadecimal strings for use in digital systems, such as color codes in web development.
  • Debugging or logging in systems that require hexadecimal notation.
  • Preparing data for protocols or file formats that use hexadecimal representation.

hex() Real-World Example

Let’s say you need to convert a list of decimal RGB values into their hexadecimal color code equivalents for use in web design.

Language: Python
>>> rgb_values = [255, 165, 0]
>>> hex_colors = [hex(value)[2:] for value in rgb_values]  # Strip the '0x' prefix
>>> hex_color_code = '#' + ''.join(hex_colors)
>>> hex_color_code
'#ffa500'

In this example, the hex() function is used to convert each RGB component to its hexadecimal equivalent, allowing you to generate a valid hex color code for web use.

Tutorial

Python Built-in Functions: A Complete Guide

Use Python's built-in functions for math, data types, iterables, and I/O to write shorter, more Pythonic code.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Feb. 4, 2026 • Reviewed by Dan Bader