On Mon, Jul 19, 2010 at 03:59, Alan Gauld <alan.ga...@btinternet.com> wrote: > "Richard D. Moores" <rdmoo...@gmail.com> wrote >> >> Still, I understand yours, and not his (the return line). > > return "%0*d" % (n, random.randrange(10**n)) > > "%0*d" > > The asterisk is quite unusual but basically means substitute the next > argument but treat it as part of the format string. So: > >>>> "%0*d" % (2,8) # becomes same as "%02d" > > '08' >>>> >>>> "%0*d" % (7,8) # becomes same as "%07d" > > '0000008' > > So for the return statement with n = 4 it would give > "%04d" % x > > where x is a random number from range(10000). > That becomes > > 0dddd > > where dddd is the random number
Just tried it with 4 and executed many times. Seems the 0 in 0dddd is there when a dddd is a 3-digit number such as 123. In that case a zero is prefixed to 123 to produce 0123. Or if just 23, 2 zeros are prefixed, etc. Correct? > > > The same thing can be done in two steps with: > > fmt = "%0%dd" % n # eg. gives "%04d" if n is 4 > return fmt % randrange(....) > > But the asterisk is neater (and faster) but can become hard to read, and > debug, if over-used - like if there are many arguments in a single string! > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist - tu...@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor