Formatting numbers with leading zeros (zero-padding) is a common requirement in programming. Whether you are generating sequential filenames, normalizing ID numbers, or formatting timestamps, Python provides multiple ways to achieve this.
This guide explores the four primary methods for zero-padding numbers: f-strings (the modern standard), the .format() method, the legacy % operator, and the string-specific .zfill() method.
Method 1: Using f-strings (Recommended)
Introduced in Python 3.6, f-strings are the most concise and readable way to format numbers. You specify the desired width inside the curly braces.
Syntax: f"{value:0width}"
0: Indicates zero-padding.width: The total character length of the output string.
number = 42
formatted = f"{number:05d}"
print(f"Integer: {formatted}")
pi = 3.14
formatted_float = f"{pi:08.2f}"
print(f"Float: {formatted_float}")Output:
Integer: 00042
Float: 00003.14Method 2: Using the .zfill() Method
The string method .zfill(width) (zero fill) is designed specifically for this purpose. It pads a numeric string on the left with zeros until the specified width is reached. It handles negative signs correctly.
num_str = "42"
neg_str = "-42"
print(f"Positive: {num_str.zfill(5)}")
print(f"Negative: {neg_str.zfill(5)}")Output:
Positive: 00042
Negative: -0042Method 3: Using .format() and % Operator
These are older methods but are still widely used in legacy codebases.
The .format() Method
Similar to f-strings but compatible with Python < 3.6.
number = 123
print("Format: {:010d}".format(number))Output:
Format: 0000000123The % Operator (Legacy)
Inherited from C style formatting.
number = 7
print("Legacy: %03d" % number)Output:
Legacy: 007Practical Example: Generating Filenames
A common real-world use case involves creating sequential filenames (e.g., log_01.txt, log_02.txt) to ensure they sort correctly in file explorers.
import datetime
def generate_log_filename(index):
now = datetime.datetime.now()
date_part = f"{now.year}{now.month:02d}{now.day:02d}"
id_part = f"{index:04d}"
return f"log_{date_part}_{id_part}.txt"
for i in range(1, 4):
print(generate_log_filename(i))Output:
log_20251227_0001.txt
log_20251227_0002.txt
log_20251227_0003.txtConclusion
To format numbers with a zero prefix in Python:
- Use F-Strings (
f"{n:05d}") for modern, readable code. - Use
.zfill(5)if you are already working with strings. - Use
.format()or%only when maintaining legacy code.