Pad strings and numbers with zeros in Python
Use zfill for signed strings, numeric format specifications for integers, and rjust or ljust when you need literal character padding.
Use text.zfill(width) to add leading zeros to a string. For an integer, use a numeric format such as f"{number:05d}". Both produce strings with a minimum width; neither truncates a value that is already longer.
Pad an existing string
print("123".zfill(5)) # 00123
print("123456".zfill(3)) # 123456
print("-123".zfill(6)) # -00123
print("+123".zfill(6)) # +00123
zfill places zeros after a leading ASCII plus or minus sign. It does not validate whether the rest of the string is a number.
Format an integer
number = 42
print(f"{number:05d}") # 00042
print(f"{number:08d}") # 00000042
print(f"{-42:05d}") # -0042
Here, d selects decimal integer formatting, 5 is the minimum total width, and 0 requests sign-aware zero padding. The sign counts toward that width.
This is useful when generating identifiers:
for number in range(1, 11):
print(f"item_{number:03d}")
The output runs from item_001 through item_010.
Use literal left or right padding
print("123".rjust(5, "0")) # 00123
print("-123".rjust(6, "0")) # 00-123
print("123".ljust(5, "0")) # 12300
rjust treats the sign as an ordinary character. It is useful for general text alignment, whereas zfill and numeric formatting usually fit signed numbers better. ljust pads the right side; for numeric text, that changes the represented value.
FAQ
Is the result still numeric? No. Keep the original numeric value for arithmetic and comparison, and format it when displaying it. Converting "00042" back with int() produces 42 and loses the leading zeros.
Can I use a different fill character? Yes, rjust and ljust accept a single-character fill argument. Use them when padding is about layout rather than numeric representation.
References
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan