A useful, but painful, one-liner to edit money amounts
steve-REMOVE-THIS at cybersource.com.au
Thu Aug 5 08:20:58 CEST 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,
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
>>> group_digits(1234567890, 4, ';')
Additional error checking, a better docstring, and extending it to
support negative numbers is left as an exercise.
More information about the Python-list