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.