The Python Oracle

How do I pad a string with zeroes?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Riding Sky Waves v001

--

Chapters
00:00 Question
00:21 Accepted answer (Score 3188)
00:51 Answer 2 (Score 458)
01:10 Answer 3 (Score 200)
01:33 Answer 4 (Score 166)
02:06 Thank you

--

Full question
https://stackoverflow.com/questions/3390...

Accepted answer links:
[String formatting documentation]: https://docs.python.org/3/library/string...

Answer 2 links:
[rjust]: https://docs.python.org/3/library/stdtyp...

Answer 3 links:
[string formatting]: https://docs.python.org/3/library/string...
[f-strings]: https://docs.python.org/3/reference/lexi...

Answer 4 links:
[f-strings]: https://docs.python.org/3/reference/lexi...
[Python 2.6]: https://docs.python.org/2.6/library/stdt...
[standard format specifiers]: https://docs.python.org/3/library/string...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #string #zeropadding

#avk47



ACCEPTED ANSWER

Score 3440


To pad strings:

>>> n = '4'
>>> print(n.zfill(3))
004

To pad numbers:

>>> n = 4
>>> print(f'{n:03}') # Preferred method, python >= 3.6
004
>>> print('%03d' % n)
004
>>> print(format(n, '03')) # python >= 2.6
004
>>> print('{0:03d}'.format(n))  # python >= 2.6 + python 3
004
>>> print('{foo:03d}'.format(foo=n))  # python >= 2.6 + python 3
004
>>> print('{:03d}'.format(n))  # python >= 2.7 + python3
004

String formatting documentation.




ANSWER 2

Score 496


Just use the rjust method of the string object.

This example creates a 10-character length string, padding as necessary:

>>> s = 'test'
>>> s.rjust(10, '0')
>>> '000000test'



ANSWER 3

Score 220


Besides zfill, you can use general string formatting:

print(f'{number:05d}') # (since Python 3.6), or
print('{:05d}'.format(number)) # or
print('{0:05d}'.format(number)) # or (explicit 0th positional arg. selection)
print('{n:05d}'.format(n=number)) # or (explicit `n` keyword arg. selection)
print(format(number, '05d'))

Documentation for string formatting and f-strings.




ANSWER 4

Score 75


>>> '99'.zfill(5)
'00099'
>>> '99'.rjust(5,'0')
'00099'

if you want the opposite:

>>> '99'.ljust(5,'0')
'99000'