iterating in reverse
Steve Holden
sholden at holdenweb.com
Fri Jan 17 15:23:56 EST 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".
def commafy(val):
val = str(val)
if len(val) < 4:
return val
chunk = [3, 1, 2]
out = []
while val:
n = chunk[len(val) % 3]
out.append(val[:n])
val = val[n:]
return ",".join(out)
for i in [1, 12, 123, 1234, 12345, 123456, 1234567, 12345678]:
print i, ":", commafy(i)
I've even tested it.
regards
--
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
mailing list