20

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.

2 Answers 2

39

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way to achieve the same result (dynamically calculated padding) when using f-strings?
@albert it works exactly the same way using f-strings. Given number, width = 4, 2, f"{number:0{width}d}" produces '04'.
3

Yes, it's possible

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.