When handling ID numbers, dates, or filenames (e.g., image_001.jpg), you often need to fill the missing parts with “0” to align the number of digits. This process is called “zero-padding.”
In Python, there are two common ways to achieve this: using the string method zfill() and using f-strings (formatted string literals).
In this article, I will explain how to use each method and when to use which.
Table of Contents
- Using the String Method:
zfill() - Using f-strings (Recommended)
- Summary
1. Using the String Method: zfill()
zfill() is a method available for strings (str type). It pads the string with zeros on the left side until it reaches the specified length (width).
Syntax:
string_variable.zfill(total_length)
To use this method, the target must be a string. If you are dealing with numbers, you must convert them using str() first.
Specific Use Case
Here is an example of formatting a user ID to 4 digits.
# Original data (number)
user_id_num = 92
# 1. Convert to string
user_id_str = str(user_id_num)
# 2. Zero-pad to 4 digits using zfill
formatted_id = user_id_str.zfill(4)
print(f"Original: {user_id_str}")
print(f"Padded : {formatted_id}")
Execution Result:
Original: 92
Padded : 0092
If your data is already a string (for example, read from a CSV file), zfill() is the easiest way to handle it.
Handling Signs
zfill() recognizes signs (plus or minus) and handles them appropriately. The “0” is inserted after the sign.
print("-42".zfill(5))
Execution Result:
-0042
(It becomes 5 characters long, including the -).
2. Using f-strings (Recommended)
For Python 3.6 and later, using f-strings (formatted string literals) is recommended. The advantage of this method is that you do not need to convert numbers to strings manually.
Syntax:
f"{number:0width}"
Writing :05 means “pad with 0 to make it 5 digits long.”
Specific Use Case
Here is an example of formatting date data.
year = 2025
month = 4
day = 1
# Zero-pad month and day to 2 digits (:02)
# You can embed int types directly
date_str = f"{year}-{month:02}-{day:02}"
print(date_str)
Execution Result:
2025-04-01
Since the code becomes very concise, this is the best practice when dealing with numeric variables.
Specifying Width with a Variable
If you want to specify the digit width using a variable, you can nest the curly braces.
number = 7
width = 3
# Zero-pad using the 'width' variable
print(f"{number:0{width}}")
Execution Result:
007
Summary
string.zfill(width): Use this if your data is already a “string” or if you are working with older Python versions.f"{number:0width}": Use this if your data is a “number”. It is the most efficient and readable method.
