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

Steven D'Aprano steve-REMOVE-THIS at cybersource.com.au
Thu Aug 5 02:20:58 EDT 2010


On Wed, 04 Aug 2010 21:33:31 -0700, 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])

What does the name "editmoney" mean? 

Why the obfuscated one-liner? It's not like you're using it in-line, 
you're putting it in a function, so who cares if it's one line or twenty?

def group_digits(n, size=3, sep=','):
    """Group int n in groups of size digits separated by sep."""
    s = str(n)
    m = len(s) % size
    head = s[0:m]
    tail = s[m:]
    groups = [tail[i*size:(i+1)*size] for i in range(len(tail)//size)]
    tail = sep.join(groups)
    if head and tail:
        return head + sep + tail
    elif tail:
        return tail
    else:
        return head


>>> group_digits(0)
'0'
>>> group_digits(1234567890)
'1,234,567,890'
>>> group_digits(1234567890, 4, ';')
'12;3456;7890'


Additional error checking, a better docstring, and extending it to 
support negative numbers is left as an exercise.



-- 
Steven



More information about the Python-list mailing list