John Posner wrote:
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.
You don't need to reverse the string:
def thous_format(integer_string):
"""
add comma thousands separator(s) to an integer-valued string
"""
return re.sub(r"(?<=\d)(?=(?:\d\d\d)+$)", ",", integer_string)
--
http://mail.python.org/mailman/listinfo/python-list