How to Pad a String with Zeros in Python
Pad a string to a fixed width by left-filling it with zeros using the built-in str.zfill method.
Python code
8 linesdef pad_zeros(s, width):
return s.zfill(width)
if __name__ == "__main__":
print(repr(pad_zeros("42", 6)))
print(repr(pad_zeros("-7", 5)))
print(repr(pad_zeros("hello", 10)))
print(repr(pad_zeros("123", 3)))
Output
'000042'
'-0007'
'00000hello'
'123'
How it works
The str.zfill(width) method returns a copy of the string left-filled with ASCII '0' digits to make a string of length width. A leading sign prefix ('+' or '-') is handled correctly: the zeros appear after the sign, so '-7'.zfill(5) becomes '-0007'. If the original string is already at least as long as width, it is returned unchanged, as shown with '123'.zfill(3). Since zfill is a method on str, it works for any string, not just numeric ones.
Common mistakes
- Using ljust('0') which pads on the right instead of the left
- Confusing zfill with string formatting that might not handle signs the same way
- Forgetting that zfill does not truncate; it only pads when the width is larger than the string length
Variations
- Use f-string formatting for integers: f'{42:05d}'
- Use str.format with format spec: '{:0>6}'.format('42')
Real-world use cases
- Formatting numeric IDs or order numbers to a consistent length for display or sorting.
- Preparing fixed-width fields for file exports like CSV or log lines where alignment matters.
- Creating zero-padded date or time components (e.g., '07' for month) before concatenating strings.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.