Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting a replacement from dictionary

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?

like image 248
EhmKah a.k.a. Michael Krauße Avatar asked Feb 06 '26 06:02

EhmKah a.k.a. Michael Krauße


2 Answers

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.

like image 137
Anand S Kumar Avatar answered Feb 09 '26 12:02

Anand S Kumar


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
like image 20
Martijn Pieters Avatar answered Feb 09 '26 11:02

Martijn Pieters