How to Pad Number with Leading Zeros in Python
In Python, you can pad a number with leading zeros using
str.zfill(width), format() with format specifiers like "{:0widthd}", or f-strings such as f"{num:0{width}d}". These methods convert the number to a string with zeros added at the start to reach the desired length.Syntax
Here are common ways to pad numbers with leading zeros in Python:
str.zfill(width): Pads the string with zeros on the left to reachwidth.format()orf-strings: Use format specifiers like"{:0widthd}"wherewidthis the total length.
Replace width with the total number of digits you want.
python
num = 42 # Using zfill str_num = str(num).zfill(5) # '00042' # Using format() str_num2 = "{:05d}".format(num) # '00042' # Using f-string str_num3 = f"{num:05d}" # '00042'
Example
This example shows how to pad the number 7 with leading zeros to make it 4 digits long using three methods.
python
num = 7 width = 4 # Using zfill padded1 = str(num).zfill(width) # Using format() padded2 = "{:0{}d}".format(num, width) # Using f-string padded3 = f"{num:0{width}d}" print(padded1) print(padded2) print(padded3)
Output
0007
0007
0007
Common Pitfalls
Common mistakes include:
- Trying to pad numbers directly without converting to string (only string methods like
zfill()work). - Using incorrect format specifiers that don't pad zeros.
- Confusing the width parameter with the number of zeros to add (width is total length).
Always ensure you convert numbers to strings if using string methods, or use proper format specifiers.
python
num = 5 # Wrong: zfill on int (raises error) # padded_wrong = num.zfill(3) # AttributeError # Right: padded_right = str(num).zfill(3) # '005' # Wrong: format without zero padding padded_wrong2 = "{:3d}".format(num) # ' 5' (spaces, not zeros) # Right: padded_right2 = "{:03d}".format(num) # '005'
Quick Reference
| Method | Syntax | Description |
|---|---|---|
| zfill | str(num).zfill(width) | Pads string with zeros to total length width |
| format() | "{:0widthd}".format(num) | Formats number with leading zeros to width |
| f-string | f"{num:0{width}d}" | Same as format(), modern and readable |
Key Takeaways
Use str.zfill(width) to pad numbers converted to strings with leading zeros.
Format specifiers like {:0widthd} in format() or f-strings add leading zeros easily.
Width means total length including the number, not just zeros to add.
Always convert numbers to strings before using string methods like zfill.
f-strings provide a clean and modern way to pad numbers with zeros.