[Tutor] A file containing a string of 1 billion random digits.
Alan Gauld
alan.gauld at btinternet.com
Mon Jul 19 12:59:05 CEST 2010
"Richard D. Moores" <rdmoores at 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
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/
More information about the Tutor
mailing list