iterating in reverse

Cliff Wells LogiplexSoftware at earthlink.net
Fri Jan 17 20:15:11 CET 2003


On Fri, 2003-01-17 at 10:15, Nick Vargish 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.

Here's a variation:

def commafy(val):
    """Return val as string with commas every thousandth place."""
    val = list(str(val))
    ret = ''
    c = 0
    while val:
        i = val.pop()
        if c and not c % 3:
            ret = ',' + ret
        ret = i + ret
        c += 1
    return ret


-- 
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726 x308  (800) 735-0555 x308






More information about the Python-list mailing list