Use the format() function with a '02x' format.

>>> format(255, '02x')
'ff'
>>> format(2, '02x')
'02'

The 02 part tells format() to use at least 2 digits and to use zeros to pad it to length, x means lower-case hexadecimal.

The Format Specification Mini Language also gives you X for uppercase hex output, and you can prefix the field width with # to include a 0x or 0X prefix (depending on wether you used x or X as the formatter). Just take into account that you need to adjust the field width to allow for those extra 2 characters:

>>> format(255, '02X')
'FF'
>>> format(255, '#04x')
'0xff'
>>> format(255, '#04X')
'0XFF'
Answer from Martijn Pieters on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › what does the '::' do and "'%02x%02x%02x' %"?
r/learnpython on Reddit: What does the '::' do and "'xxx' %"?
August 18, 2019 -
import colorsys
import time

def drawRainbow():
  with open("/sys/devices/platform/system76/leds/system76::kbd_backlight/color_left", "r+") as f:
    for i in range(1000):
        r, g, b = colorsys.hsv_to_rgb(i/100, 1.0, 1.0)
        hexcolor = '%02x%02x%02x' % (int(r*255), int(g*255), int(b*255))
        f.write(hexcolor)
        f.flush()
        time.sleep(2)

while True:
    drawRainbow()

I'm trying to read through the code, but I'm not quite sure what to make of those two parts. Could someone explain? The '%' I know is a modulus operator, but I don't quite understand how to apply that to the particular line of code.

🌐
The Teclado Blog
blog.teclado.com › python-formatting-integers-in-different-bases
Formatting Integers in Different Bases in Python
June 25, 2026 - The syntax for this is :02x, which means represent the number as hexadecimal (x), display the number with two figures (2), and pad the number with zeroes if we have fewer than two figures (0).
🌐
Reddit
reddit.com › r/learnpython › map('{:02x}'.format, bytes_addr)
r/learnpython on Reddit: map('{:02x}'.format, bytes_addr)
May 1, 2018 -

Hello all,

I am having trouble understanding what this statement does. This statement is supposed to help me format mac addresses as they are received, but I don't see why we would need to format mac addresses to two decimal places when mac addresses don't have decimals. Am I missing something?

🌐
Finxter
blog.finxter.com › home › learn python blog › python int to hex | string formatting
Python Int to Hex | String Formatting - Be on the Right Side of Change
November 16, 2022 - You can use the format specifer 02X to convert an integer to a fixed-width hex string with 2 positions, and filling the remaining positions with '0' symbols from the left.
🌐
Python
docs.python.org › 3 › library › string.html
string — Common string operations
>>> for align, text in zip('<^>', ['left', 'center', 'right']): ... '{0:{fill}{align}16}'.format(text, fill=align, align=align) ... 'left<<<<<<<<<<<<' '^^^^^center^^^^^' '>>>>>>>>>>>right' >>> >>> octets = [192, 168, 0, 1] >>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets) 'C0A80001' >>> int(_, 16) 3232235521 >>> >>> width = 5 >>> for num in range(5,12): ...
🌐
Alibaba Cloud
topic.alibabacloud.com › zqpop › 02x-python_10119.html
The Latest information about 02x python | Alibaba Cloud
This paper describes the implementation of DES encryption and decryption method in Python. Share to everyone for your reference.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-convert-bytearray-to-hexadecimal-string
Convert Bytearray to Hexadecimal String - Python - GeeksforGeeks
July 12, 2025 - format(byte, '02x') ensures each byte is converted to a two-digit hexadecimal string (padded with zero if needed).
Find elsewhere
🌐
Faq Inc
faq.splendida.live › home › what is 02x in python?
What is 02x in python? - Faq
The 02x tells Python we want the number represented as a 2 digit hexadecimal number, where any missing digits are padded with zeroes.
🌐
Python
docs.python.org › 3.1 › library › string.html
7.1. string — Common string operations — Python v3.1.5 documentation
August 1, 2015 - >>> for align, text in zip('<^>', ['left', 'center', 'right']): ... '{0:{fill}{align}16}'.format(text, fill=align, align=align) ... 'left<<<<<<<<<<<<' '^^^^^center^^^^^' '>>>>>>>>>>>right' >>> >>> octets = [192, 168, 0, 1] >>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets) 'C0A80001' >>> int(_, 16) 3232235521 >>> >>> width = 5 >>> for num in range(5,12): ...
🌐
LabEx
labex.io › tutorials › python-how-to-ensure-precise-hex-formatting-436768
How to ensure precise hex formatting | LabEx
By mastering these formatting techniques, you'll gain precise control over hexadecimal representation in Python, enhancing your data manipulation skills across various programming scenarios. class ColorConverter: @staticmethod def rgb_to_hex(r, g, b): return f'#{r:02x}{g:02x}{b:02x}' @staticmethod def hex_to_rgb(hex_color): hex_color = hex_color.lstrip('#') return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4)) ## Usage example red = ColorConverter.rgb_to_hex(255, 0, 0) print(red) ## #ff0000 ·
🌐
Medium
medium.com › @bhanotkaran22 › hey-nitin-97e301ee2ead
Hey Nitin,. Let’s consider the case {0:02x}. | by Karan Bhanot | Medium
June 9, 2019 - Hey Nitin, Let’s consider the case {0:02x}. Whenever we want to specify a format of our string, we include it in curly braces {}. Taking a look at the example here, the number before : defines the …
🌐
Picuino
picuino.com › en › python-textos-formateo.html
24. Formatting text strings - Python tutorial - Picuino
June 13, 2026 - Remember that hexadecimal values ​​must be in capital letters and must have two digits. The way to convert a variable to hexadecimal that always has two digits is to add the following format to the variable: f'{variable:02X}'.
🌐
Pythoncomplexity
pythoncomplexity.com › builtins › hex
Hex - Python Big-O: Time & Space Complexity
# O(log n) - RGB values to hex color def rgb_to_hex(r, g, b): # O(log(256)) = O(8) per channel return f"#{hex(r)[2:]:>02}{hex(g)[2:]:>02}{hex(b)[2:]:>02}" color = rgb_to_hex(255, 128, 64) # '#ff8040' # Converting from integers red = 255 green = 128 blue = 64 color_hex = f"#{red:02x}{green:02x}{blue:02x}" # Cleaner with format strings
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › using the raspberry pi › beginners
Changing Hex String - Raspberry Pi Forums
You don't even have to fuss with hex values: playcmd(1,180) would return the same, as would playcmd(m, s) if you'd set m=1 and s=180 (= 0xb4) beforehand. The code above uses the older Python % formatting operator, which works just like other languages' sprintf() function.
🌐
w3resource
w3resource.com › python-exercises › python-basic-exercise-141.php
Python: Convert decimal to hexadecimal - w3resource
May 17, 2025 - # It ensures that there are leading ... of 'x' with leading zeros. # The 'format' function is used with the format specifier '02x' to format 'x' as a 2-character lowercase hexadecimal string....
🌐
Stack Overflow
stackoverflow.com › questions › 54283039 › 02x02x02x02x-formatoctets-c0a80001
python - '{:02X}{:02X}{:02X}{:02X}'.format(*octets) 'C0A80001' - Stack Overflow
January 21, 2019 - I read the string — Common string operations — Python 3.7.2 documentation · The below example is easy to follow: >>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42) 'int: 42; hex: 2a; oct: 52; bin: 101010' As to the instance · >>> octets = [192, 168, 0, 1] >>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets) 'C0A80001 ·
🌐
Finxter
blog.finxter.com › home › learn python blog › 5 best ways to convert python rgb tuples to hex
5 Best Ways to Convert Python RGB Tuples to Hex - Be on the Right Side of Change
February 22, 2024 - An easy way to convert an RGB tuple to a hexadecimal string in Python is by using string format specification. This method takes advantage of the format mini-language built into Python where '{:02x}' specifies a hex format.