iterating in reverse
sholden at holdenweb.com
Fri Jan 17 21:23:56 CET 2003
"Paul Rubin" <phr-n2003b at NOSPAMnightsong.com> wrote in message
news:7xznpzv93c.fsf at ruckus.brouhaha.com...
> Nick Vargish <nav at adams.patriot.net> writes:
> > I just encountered a problem that required reverse iterating to solve,
> > and my current solution, though it works, is not so satisfying:
> > def commafy(val):
> > """Return val as string with commas every thousandth place.""" ...
> If you're just looking for a practical solution, use the locale package,
> which does this formatting for you.
That's no fun.
Here's my own non-reversing solution. Again, it would need tweaking for
negative numbers to avoid results like "-,123".
val = str(val)
if len(val) < 4:
chunk = [3, 1, 2]
out = 
n = chunk[len(val) % 3]
val = val[n:]
for i in [1, 12, 123, 1234, 12345, 123456, 1234567, 12345678]:
print i, ":", commafy(i)
I've even tested it.
Steve Holden http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/pwp/
Bring your musical instrument to PyCon! http://www.python.org/pycon/
More information about the Python-list