iterating in reverse

Richard Kuhns rjkuhns at geetel.net
Fri Jan 17 14:22:52 EST 2003


On 17 Jan 2003 13:15:21 -0500
Nick Vargish <nav at adams.patriot.net> wrote:

> 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."""
>     val = str(val)
>     ret = ''
>     c = 0
>     for i in range(len(val) - 1, -1, -1):
>         if c and not c % 3:
>             ret = ',' + ret
>         ret = val[i] + ret
>         c += 1
>     return ret
> 
> This is one of the few times I just haven't been able to come up with
> an elegant and -- dare I say it -- aesthetically pleasing solution in
> Python. I suspect the lack is my own, not Python's.
> 
> Nick

Here's the one I use:

def comify(number):
    import re
    string, count = re.subn(r'^(-?\d+)(\d\d\d)', r'\1,\2', str(number))
    while count > 0:
        string, count = re.subn(r'^(-?\d+)(\d\d\d)', r'\1,\2', string)
    return string

-- 
Richard Kuhns			rjkuhns at geetel.net





More information about the Python-list mailing list