Nicest way to pad zeroes to a string


Question

What is the most Pythonic way to pad a numeric string with zeroes to the left, i.e., so the numeric string has a specific length?

1
1235
5/5/2019 1:26:28 AM

Accepted Answer

Strings:

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

And for numbers:

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

String formatting documentation.

2037
1/25/2019 2:18:15 AM

Just use the rjust method of the string object.

This example will make a string of 10 characters long, padding as necessary.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon