The Python Oracle

How do I pad a string with zeroes?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Mysterious Puzzle

--

Chapters
00:00 How Do I Pad A String With Zeroes?
00:13 Answer 1 Score 220
00:31 Accepted Answer Score 3440
00:51 Answer 3 Score 496
01:06 Answer 4 Score 75
01:14 Thank you

--

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

--

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'