Python String zfill()
Method
The zfill() method in Python is used to pad a numeric string with leading zeros, so that the resulting string reaches a specified length. It's especially useful when formatting numbers like invoice IDs, codes, or timestamps.
Syntax
string.zfill(width)
Parameter:
width
– The total length of the resulting string (including leading zeros).
Returns:
- A copy of the string left-padded with zeros to make it at least
width
characters long.
Example 1: Simple Zero Padding
text = "42"
print(text.zfill(5))
00042
Example 2: zfill() with Negative Numbers
text = "-42"
print(text.zfill(5))
-0042
Note: The negative sign is preserved in its original position.
Example 3: No Padding if Already Long Enough
text = "12345"
print(text.zfill(4))
12345
The string remains unchanged because its length is already more than the specified width.
Use Cases
- Formatting IDs with fixed length (e.g., invoice IDs like
INV000123
) - Preparing data for export to systems that require zero-padded numbers
- Display time values like
05
instead of5
Common Mistakes
- Using
zfill()
on non-string types like integers will raise an error. Convert to string first. - Confusing
zfill()
withrjust()
orljust()
which pad with spaces by default.
Interview Tip
zfill()
is handy in problems requiring fixed-width formatting or normalization of numeric string data before comparison.
Summary
zfill()
pads the string on the left with0
s until it reaches the specified length.- It preserves the sign position for negative numbers.
- Only works on string types — use
str()
on numbers before callingzfill()
.
Practice Problem
Write a program that asks the user for a number and prints it as a 6-digit zero-padded string.
user_input = input("Enter a number: ")
print("Padded Number:", user_input.zfill(6))