Daniel Gorelik
Daniel Gorelik

Reputation: 289

Dynamically calculated zero padding in format string in python

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.

Upvotes: 20

Views: 11844

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1123440

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.

Upvotes: 39

roman
roman

Reputation: 117485

Yes, it's possible

>>> print "%0*d" % (5, 4)
00004
>>> print "%0*d" % (10, 4)
0000000004

Upvotes: 3

Related Questions