python - How to pad leading zero (in a function) dynamically? -
i know "%03d"
can pretty easily, i'm trying solve different problem. part of script, need find out how many numbers in range (e.g. 0-999) have @ lest 1 3 (or digit in question) in it. so, came lambda function:
fx = lambda z,y=999: [ "%03d" % (x, ) x in range(y) if str(z) in str(x) ]
which working great want automate padding 'leading zero' bit according range e.g. 003 when it's 999 or 09 88 , on. idea how can that?
if want pass dynamic width formatting functions, can:
>>> width = 5 >>> value = 2 >>> '%0*d' % (width, value) '00002'
it's easier new-style formatting, because can embed placeholders inside placeholders:
>>> width = 5 >>> value = 2 >>> '{1:0{0}}'.format(width, value) '00002'
if want know how longest value in of values before outputting them, long can iterate on values twice, that's pretty easy:
>>> values = 3, 100, 50000 >>> width = max(len('%0d' % value) value in values) >>> ', '.join('%0*d' % (width, value) value in values) '00003, 00100, 50000'
and if want base on parameter, that's easier:
fx = lambda z,y=999: [ "%0*d" % (len('%0d' % y), x) x in range(y) if str(z) in str(x) ]
however, that's going calculate width of y
on , on again, because inside expression there's no easy way store it, , lambda
can take expression.
which raises question of why you're using lambda
in first place. advantage of lambda
on def
can use in expression , don't need come name it. if you're going assign name, eliminates both advantages. so, this:
def fx(z, y=999): width = len('%0d' % y) return ["0%*d" % (width, x) x in range(y) if str(z) in str(x)]
Comments
Post a Comment