How to pad zeros to a String in Python
This article shows how to pad a numeric string with zeroes to the left such that the string has a specific length.
This article shows how to pad a numeric string with zeroes to the left such that the string has a specific length.
#more
It also shows how numbers can be converted to a formatted String with leading zeros.
Use str.zfill(width)
¶
zfill is the best method to pad zeros from the left side as it can also handle a leading '+' or '-' sign.
It returns a copy of the string left filled with '0' digits to make a string of length width. A leading sign prefix ('+'/'-') is handled by inserting the padding after the sign character rather than before. The original string is returned if width is less than or equal to len(s).
>>> "42".zfill(5)
'00042'
>>> "-42".zfill(5)
'-0042'
Use str.rjust(width[, fillbyte])
¶
If you want to insert an arbitrary character on the left side, use rjust. It returns a copy of the object right justified in a sequence of length width. The default filling character is a space. However, this does not handle a sign prefix.
>>> "42".rjust(5)
' 42'
>>> "42".rjust(5, "0")
'00042'
>>> "-42".rjust(5, "0")
'00-42'
Numbers can be padded with string formatting¶
Converted a number to a formatted string with leading zeros by using string formatting:
n = 42
print(f'{n:05d}')
print('%05d' % n)
print('{0:05d}'.format(n))
# --> all will output the same:
# '00042'
# '00042'
# '00042'
See more in the String formatting documentation
FREE VS Code / PyCharm Extensions I Use
✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*
Python Problem-Solving Bootcamp
🚀 Solve 42 programming puzzles over the course of 21 days: Link*