On Aug 5, 12:33 pm, John Nagle <na...@animats.com> wrote: > There's got to be a better way to do this: > > def editmoney(n) : > return((",".join(reduce(lambda lst, item : (lst + [item]) if > item else lst, > re.split(r'(\d\d\d)',str(n)[::-1]),[])))[::-1]) > > >>> editmoney(0) > '0' > >>> editmoney(13535) > '13,535' > >>> editmoney(-14535) > '-14,535' > >>> editmoney(123456) > '123,456' > >>> editmoney(1234567890) > '1,234,567,890' > >>> editmoney(-1234) > '-1,234' > > The basic idea here is that we want to split the string of digits > into groups of 3 digits, aligned at the right. Because regular > expressions are right to left, we have to reverse the string to > do that, then reverse again at the end. s[::-1} reverses an > interable. > > "split" with a capturing group introduces empty strings into the > list. Hence the "reduce" and lambda to get rid of them. > > Any better ideas? > > (Yes, I know there's a built-in feature for this scheduled for > Python 2.7.) > > John Nagle
In [1]: '{:,}'.format(-12345678) Out[1]: '-12,345,678' -- http://mail.python.org/mailman/listinfo/python-list