Computer >> Computer tutorials >  >> Programming >> Python

How to get a string leftpadded with zeros in Python?


We can use the rjust(width[, fillchar]) method in string class that right justifies the string and pads the left side with given filler char. The default filler char is space. You can use it as follows:

>>> '25'.rjust(6, '0')
'000025'
>>> 'Apollo'.rjust(10, '0')
'0000Apollo'

We can also use Python string formatting to achieve this result as follows:

>>> print "%06d" % 25
'000025'

We can also use the zfill method that was specifically built for the pupose of left padding zeros as follows:

>>> '25'.zfill(6)
'000025'
>>> 'Apollo'.zfill(10)
'0000Apollo'