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

John Posner jjposner at optimum.net
Thu Aug 5 10:01:59 EDT 2010


On 8/5/2010 12:33 AM, John Nagle 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])
>

Here's a more elegant variant, using regexp lookahead:

def thous_format(integer_string):
     """
     add comma thousands separator(s) to an integer-valued string
     """
     return re.sub(r'(\d{3})(?=\d)', r'\1,', integer_string[::-1])[::-1]

I *thought* that I had found this on python-list on or about July 5, but 
I didn't find the thread after a search through the archives.

-John



More information about the Python-list mailing list