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

geremy condra debatem1 at gmail.com
Thu Aug 5 03:22:57 EDT 2010


On Wed, Aug 4, 2010 at 11:30 PM, Peter Otten <__peter__ at web.de> wrote:
> 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])
>>
>>
>>  >>> 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.)
>
>
>>>> locale.setlocale(locale.LC_ALL, ("en_US", "UTF-8"))
> 'en_US.UTF8'
>>>> print locale.currency(13535, grouping=True)
> $13,535.00
>>>> print locale.format("%d", 13535, grouping=True)
> 13,535
>
>>>> locale.setlocale(locale.LC_ALL, "")
> 'de_DE.UTF-8'
>>>> print locale.currency(13535, grouping=True)
> 13.535,00 €
>>>> print locale.format("%d", 13535, grouping=True)
> 13.535
>
> Peter

I had literally no idea this existed. Thanks.

Geremy Condra



More information about the Python-list mailing list