Martin Walsh wrote: > def addcommas(f): > """ > This amounts to reversing everything left > of the decimal, grouping by 3s, joining > with commas, reversing and reassembling. > """ > # assumes type(f) == float > left, right = ('%0.2f' % f).split('.') > rleft = [left[::-1][i:i+3] for i in range(0, len(left), 3)] > return ','.join(rleft)[::-1] + '.' + right
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)) _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor