I use a dictionary for formatting a string with:
print '%(duration)s' % {'duration':'898'}
Everything works as expected. Now I want to make sure the replacement for %(duration) will be filled with zeros on the left so it has 5 digits. Result should look like: ''00898'' It is guaranteed that duration will never has more 5 digits.
How would '%(duration)s' look like?
I would prefer to use str.format here. Example -
In [46]: "{duration:0>5}".format(duration='898')
Out[46]: '00898'
If you want to use a dictionary, you can unpack the dictionary into the arguments for .format . Example -
In [48]: "{duration:0>5}".format(**{'duration':'898'})
Out[48]: '00898'
In this the main part is - {duration:0>5} - here the field name is before the : , the 0> after the : indicates right justifying by padding 0s and 5 indicates the amount of spaces to right justify.
You can find more information about string format syntax here.
Add a field width, with a leading 0; this will, however, only work with numbers:
print '%(duration)05d' % {'duration': 898}
Note that I changed the value to an integer, and the formatted to d.
Your total field width, including the padding, is 5 characters, and the 0 tells the string formatting code to zero-pad shorter numbers.
If conversion to int is not an option, switch to the newer str.format() method:
print '{duration:0>5s}'.format(**{'duration':'898'})
The 0> part tells the method to right-align and use 0 for padding. For details, see the Format Specification Mini-Language documentation.
Demo:
>>> print '%(duration)05d' % {'duration': 898}
00898
>>> print '{duration:0>5s}'.format(**{'duration':'898'})
00898
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With