Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Adding commas to digits (See related posts)

Copy from Marek Baczynski's code here
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/439357
def group(n, sep = ','):
    s = str(n)[::-1]
    groups = []
    i = 0
    while i < len(s):
        groups.append(s[i:i+3])
        i += 3
    return sep.join(groups)[::-1]

#>>> group(42424242)
#'42,424,242'


Comments on this post

frankwhite posts on Aug 18, 2005 at 17:56
nice
pj posts on Sep 01, 2005 at 16:36
Why not:

def group(n, sep = ','):
s = str(n)
out = ''
while len(s) > 3:
out = sep + s[-3:] + out
s = s[:-3]
return s + out

?? Less code and a bit clearer I think...

You need to create an account or log in to post comments to this site.


Click here to browse all 5140 code snippets

Related Posts