+3 votes
3 views
in Python by (4.1k 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 (46.1k 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 (107k 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

+7 votes
3 answers
+3 votes
2 answers
asked May 24, 2019 in Python by Krishna (2.6k points)
+3 votes
2 answers
+1 vote
2 answers
+3 votes
2 answers
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...