A useful, but painful, one-liner to edit money amounts

John Nagle nagle at animats.com
Thu Aug 5 06:33:31 CEST 2010

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,

 >>> editmoney(0)
 >>> editmoney(13535)
 >>> editmoney(-14535)
 >>> editmoney(123456)
 >>> editmoney(1234567890)
 >>> editmoney(-1234)

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

"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

More information about the Python-list mailing list