If you want to pass a dynamic width to the formatting functions, you can:
>>> width = 5
>>> value = 2
>>> '%0*d' % (width, value)
'00002'
It's even easier with new-style formatting, because you can embed placeholders inside placeholders:
>>> width = 5
>>> value = 2
>>> '{1:0{0}}'.format(width, value)
'00002'
If you also want to know how to get the longest value in all of the values before outputting them, as long as you can iterate over the values twice, that's pretty easy:
>>> values = 3, 100, 50000
>>> width = max(len('%0d' % value) for value in values)
>>> ', '.join('%0*d' % (width, value) for value in values)
'00003, 00100, 50000'
And if you want to base it on a parameter, that's even easier:
fx = lambda z,y=999: [ "%0*d" % (len('%0d' % y), x) for x in range(y) if str(z) in str(x) ]
However, that's going to calculate the width of y
over and over again, because inside an expression there's no easy way to store it, and a lambda
can only take an expression.
Which raises the question of why you're using a lambda
in the first place. The only advantage of lambda
over def
is that you can use it in an expression and don't need to come up with a name for it. If you're going to assign it to a name, that eliminates both advantages. So, just do this:
def fx(z, y=999):
width = len('%0d' % y)
return ["0%*d" % (width, x) for x in range(y) if str(z) in str(x)]