Question
How can I print a number or convert it to a string with leading zeros so it has a fixed width in Python?
For example, if I have the number 12, how can I display it as 000012?
Short Answer
By the end of this page, you will understand how to format numbers with leading zeros in Python, why zero-padding is useful, and how to use common tools like zfill(), format(), and f-strings to create fixed-width output.
Concept
Zero-padding means adding 0 characters to the left of a number so the final output has a specific width.
For example:
12becomes000012when the width is65becomes005when the width is3
This matters because many programs need values in a consistent format. Common examples include:
- invoice numbers like
000123 - file names like
image_001.png - log entries with aligned columns
- date and time parts like
09:05
In Python, numbers themselves do not store leading zeros in their normal decimal form. Leading zeros are usually part of string formatting, not the numeric value itself.
So the main idea is:
- keep the value as a number when you want to calculate with it
- convert or format it as a string when you want to display it with leading zeros
Mental Model
Think of a number as an object being placed into a box of fixed size.
If the box must hold 6 characters and the number is 12, Python puts 12 in the box and fills the empty spaces on the left with 0:
- box size:
6 - number:
12 - result:
000012
The number does not change mathematically. You are only changing how it looks when printed or stored as text.
Syntax and Examples
There are several common ways to pad numbers with zeros in Python.
1. Using str.zfill()
num = 12
result = str(num).zfill(6)
print(result)
Output:
000012
zfill(6) makes the string at least 6 characters wide by adding zeros to the left.
2. Using format()
num = 12
result = format(num, "06d")
print(result)
Output:
000012
Explanation:
0means pad with zeros6means total width is 6dmeans format as an integer
3. Using an f-string
num =
result =
(result)
Step by Step Execution
Consider this example:
num = 12
formatted = f"{num:06d}"
print(formatted)
Step by step:
-
num = 12- A variable named
numstores the integer12.
- A variable named
-
formatted = f"{num:06d}"- Python starts an f-string.
numis the value to format.0says to use zeros for padding.6says the total width must be 6 characters.dsays the value is an integer.- Since
12has 2 digits, Python adds 4 zeros to the left. formattedbecomes"000012".
-
print(formatted)- Python prints the final string:
Real World Use Cases
Zero-padding appears in many practical situations.
File naming
for i in range(1, 4):
print(f"image_{i:03d}.png")
Output:
image_001.png
image_002.png
image_003.png
This helps files sort correctly.
Invoice or order IDs
order_id = 27
print(f"ORD-{order_id:06d}")
Output:
ORD-000027
Time formatting
hour = 9
minute = 5
print(f"{hour:02d}:{minute:02d}")
Output:
09:05
Data export
Fixed-width text files often require exact column widths. Zero-padding helps ensure consistent formatting.
Real Codebase Usage
In real Python projects, zero-padding is usually used during output formatting, not while storing the original value.
Common patterns include:
1. Formatting at the boundary
Keep internal values numeric:
user_id = 12
Format only when displaying or exporting:
print(f"User ID: {user_id:06d}")
2. Building filenames
def build_filename(index):
return f"frame_{index:04d}.jpg"
This keeps naming consistent in scripts that generate many files.
3. Report generation
def format_row(record_number, amount):
return f"{record_number:05d} | ${amount:.2f}"
4. Validation plus formatting
Sometimes developers first validate input, then format it:
Common Mistakes
Here are common beginner mistakes when zero-padding numbers in Python.
Mistake 1: Expecting the number itself to store leading zeros
num = 000012
This is not how normal decimal integers should be written in Python. Leading zeros belong to the string representation.
Use:
num = 12
print(f"{num:06d}")
Mistake 2: Forgetting to convert to a string before zfill()
Broken code:
num = 12
print(num.zfill(6))
This fails because integers do not have a zfill() method.
Correct version:
num = 12
print(str(num).zfill(6))
Mistake 3: Using the wrong format specifier
Broken code:
num = 12
print(f"")
Comparisons
Here is a comparison of the main ways to add leading zeros in Python.
| Method | Works on | Example | Best use |
|---|---|---|---|
str(...).zfill(width) | strings after conversion | str(12).zfill(6) | Simple padding when you already have text |
format(num, "06d") | numbers | format(12, "06d") | Older but clear formatting style |
| f-string | numbers | f"{12:06d}" | Modern, readable Python code |
zfill() vs f-strings
| Feature |
|---|
Cheat Sheet
Quick reference
Pad an integer to width 6
num = 12
f"{num:06d}"
# '000012'
Using format()
format(12, "06d")
# '000012'
Using zfill()
str(12).zfill(6)
# '000012'
Format pattern
f"{value:0Nd}"
0= pad with zerosN= total widthd= integer
Example:
f"{:04d}"
FAQ
How do I add leading zeros to a number in Python?
Use string formatting such as f"{num:06d}", format(num, "06d"), or str(num).zfill(6).
What does 06d mean in Python?
0 means pad with zeros, 6 is the total width, and d means format as an integer.
Should I store numbers with leading zeros as integers?
No. Integers do not preserve leading zeros for display. Store the value as a number and format it as a string when needed.
What is the difference between zfill() and f-strings?
zfill() pads a string, while f-strings format values directly and are more flexible for mixed output.
Can I zero-pad negative numbers in Python?
Yes. Python keeps the minus sign in front, such as -00012.
What happens if the number is longer than the requested width?
Python leaves it unchanged. It does not cut off digits.
Is zfill() only for numbers?
No. It works on any string, but it is commonly used for numeric text.
Which method is most recommended in modern Python?
Mini Project
Description
Create a small Python script that generates employee badge numbers in a fixed-width format. This demonstrates how zero-padding is used in real programs to create consistent IDs for display and export.
Goal
Build a script that converts employee numbers into 6-digit badge codes with leading zeros.
Requirements
[ "Store several employee numbers in a list", "Print each number as a 6-digit zero-padded code", "Add a text prefix like BADGE- before each formatted number", "Use an f-string or another valid Python formatting method" ]
Keep learning
Related questions
Automatic Build Versioning in Go: Embed Incrementing Build Numbers
Learn how to add automatic build versioning in Go using linker flags, build metadata, CI counters, and Git-based version values.
Blank Identifier Imports in Go: What `_` Means in an Import Statement
Learn what `_` means in a Go import, why blank identifier imports run package init code, and when to use them safely.
Calling Functions Across Files in the Same Go Package
Learn how Go uses packages across multiple files, why functions may appear undefined, and how to organize code correctly.