How to Format Numbers with Zero Prefix (Zero Padding) in Python
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
# ✅ Correct: Pad with zeros to a width of 5
formatted = f"{number:05d}"
print(f"Integer: {formatted}")
# Floating point numbers (padding includes the dot and decimals)
pi = 3.14
# Pad to width 8 (including decimals), with 2 decimal places
formatted_float = f"{pi:08.2f}"
print(f"Float: {formatted_float}")
Output:
Integer: 00042
Float: 00003.14
The d in :05d stands for integer (decimal). Use f for floating-point numbers.
Method 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"
# ✅ Correct: Using zfill on strings
print(f"Positive: {num_str.zfill(5)}")
print(f"Negative: {neg_str.zfill(5)}")
Output:
Positive: 00042
Negative: -0042
.zfill() is a string method. You must convert your integer to a string (str(number)) before calling it.
Method 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
# Syntax: "{:0width}".format(value)
print("Format: {:010d}".format(number))
Output:
Format: 0000000123
The % Operator (Legacy)
Inherited from C style formatting.
number = 7
# Syntax: "%0widthd" % value
print("Legacy: %03d" % number)
Output:
Legacy: 007
Practical 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):
# Get current timestamp
now = datetime.datetime.now()
# 1. Format date parts with leading zeros
date_part = f"{now.year}{now.month:02d}{now.day:02d}"
# 2. Format index (e.g., ID 5 -> 0005)
id_part = f"{index:04d}"
return f"log_{date_part}_{id_part}.txt"
# Generate 3 filenames
for i in range(1, 4):
print(generate_log_filename(i))
Output:
log_20251227_0001.txt
log_20251227_0002.txt
log_20251227_0003.txt
Conclusion
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.