Back

Explore Courses Blog Tutorials Interview Questions
+3 votes
4 views
in Python by (4k points)
edited by
Is there any way to pad a numeric string with zeroes to the left side in a Python script, I want it to be of a specific length?

2 Answers

0 votes
by (46k points)
edited by

It's easy just use this, 

For Strings:

>>> n = '5'
>>> print(n.zfill(4))
0005

For numbers:

>>> n = 5
>>> print('%04d' % n)
0005
>>> print(format(n, '05')) # python >= 2.6
0005
>>> print('{0:04d}'.format(n))  # python >= 2.6
0005
>>> print('{foo:04d}'.format(foo=n))  # python >= 2.6
0005
>>> print('{:04d}'.format(n))  # python >= 2.7 + python3
0005
>>> print('{0:04d}'.format(n))  # python 3
0005
>>> print(f'{n:04}') # python >= 3.6 

0005 

Happy learning,  Cheers .....!!

0 votes
by (106k points)

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

>>> t = 'test'

>>> t.rjust(10, '0')

>>> '000000test'

You can use the following video tutorials to clear all your doubts:-

Related questions

+6 votes
3 answers
+3 votes
2 answers
+3 votes
2 answers
asked May 24, 2019 in Python by Krishna (2.6k points)
+1 vote
2 answers
+3 votes
2 answers

Browse Categories

...