DZone 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

Snippets has posted 5883 posts at DZone. View Full User Profile

Adding Commas To Digits

08.18.2005
| 4337 views |
  • submit to reddit
        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

Snippets Manager replied on Mon, 2012/05/07 - 2:14pm

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...

Snippets Manager replied on Mon, 2012/05/07 - 2:14pm

nice