[Tutor] dollarize.py

Martin Walsh mwalsh at groktech.org
Mon Jun 23 00:29:36 CEST 2008


Jordan Greenberg wrote:
> def addcommas(s): # assumes type(s)==str
>     b=[]
>     l=len(s)
>     for i,v in enumerate(s):
>         i+=1 # easier to understand w/ 1-based indexing, i think.
>         b.append(v)
> 
>         if (l-i)%3==0 and not i==l:
>             b.append(',')
>     return ''.join(b)
> 
> 
> or, somewhat more tersely:
> 
> 
> def addcommas2(s):
>     l=len(s)
>     return ''.join(v+',' if (l-(i+1))%3==0 and not i+1-l==0
>                     else v for i,v in enumerate(s))


Excellent, thanks Jordan! That's much more elegant, and efficient, than
my juggling act :)


More information about the Tutor mailing list