iterating in reverse

David Eppstein eppstein at ics.uci.edu
Fri Jan 17 14:51:29 EST 2003


In article <yyywul3skw6.fsf at adams.patriot.net>,
 Nick Vargish <nav at adams.patriot.net> wrote:

> 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

def triples(s):
    i = (len(s) - 1) % 3 - 2
    while i < len(s):
        yield s[max(i,0):i+3]
        i += 3

def commafy(val):
    return ','.join(triples(str(val)))

But actually, I think your original method doesn't work so well with 
negative numbers, here's a slight modification:

def triples(s):
    i = (len(s) - 1) % 3 - 2
    if i == -2 and s[0] == '-':
        yield s[0:4]
        i = 4
    while i < len(s):
        yield s[max(i,0):i+3]
        i += 3

def commafy(val):
    return ','.join(triples(str(val)))

-- 
David Eppstein       UC Irvine Dept. of Information & Computer Science
eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/




More information about the Python-list mailing list