Dynamically calculated zero padding in format string in python

python, string-formatting

Solution

Use the `str.format()` method of string formatting instead:

'{number:0{width}d}'.format(width=2, number=4)

Demo:

>>> '{number:0{width}d}'.format(width=2, number=4)
'04'
>>> '{number:0{width}d}'.format(width=8, number=4)
'00000004'

The `str.format()` formatting specification allows for multiple passes, where replacement fields can fill in parameters for formatting specifications.

In the above example, the hard-coded padding width specification would look like:

'{:02d}'.format(4)

or

'{number:02d}'.format(number=4)

with a named parameter. I've simply replaced the `2` width specifier with another replacement field.

To get the same effect with old-style `%` string formatting you'd need to use the `*` width character:

'%0*d' % (width, number)

but this can only be used with a tuple of values (dictionary formatting is not supported) and only applies to the field width; other parameters in the formatting do not support dynamic parameters.

Problem

So I know that `"%02d to %02d"%(i, j)` in Python will zero pad `i` and `j`. But, I was wondering if there is any way to dynamically zero pad in a format string (I have a list of numbers and I want the zero pad size to be equal to the longest number in that list). I know that I could use `zfill`, but I was hoping I could do the entire thing in a format string.

Original source