I know that "%03d" can do that pretty easily, but I'm trying to solve a slightly different problem. The part of my script, I need to find out how many numbers in a range (e.g. 0-999) have at lest one 3 (or any digit in question) in it. So, I came up with this lambda function:
fx = lambda z,y=999: [ "%03d" % (x, ) for x in range(y) if str(z) in str(x) ]
which is working great but I want to automate the padding 'leading zero' bit according to the range e.g. 003 when it's 999 or 09 for 88 and so on. Any idea how can I do that?
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)]
I'm not sure it is appropriate (pythonic) or not.
Here is another solution with modern f-string.
num = 1
width = 5
out = f"{num:0{width}d}"
[0] Nested f-strings
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With