ActiveState Code

Recipe 439357: Simple digit grouping


What the title says. No more, no less. (Version 2, now supports negative numbers.)

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
def group(n, sep = ','):
    s = str(abs(n))[::-1]
    groups = []
    i = 0
    while i < len(s):
        groups.append(s[i:i+3])
        i+=3
    retval = sep.join(groups)[::-1]
    if n < 0:
        return '-%s' % retval
    else:
        return retval

Discussion

I'm sure there's a similar or better implementation somewhere in the cookbook, I was just too lazy to search properly; besides, it is so simple that I'm not sure if it even deserves an entry.

Examples:

>>> group(42)
'42'
>>> group(4242)
'4,242'
>>> group(42424242)
'42,424,242'
>>> group(42424242, "'")
"42'424'242"
>>> group(-424)
'-424'

Comments

  1. 1. At 7:49 p.m. on 18 aug 2005, Steven Bethard said:

    Note that the locale module does most of what you want here:

    py> import locale
    py> locale.setlocale(locale.LC_ALL, '')
    'English_United States.1252'
    py> locale.format('%i', 42, True)
    '42'
    py> locale.format('%i', 4242, True)
    '4,242'
    py> locale.format('%i', 424242, True)
    '424,242'
    py> locale.format('%i', 42424242, True)
    '42,424,242'
    
  2. 2. At 6:58 p.m. on 3 sep 2005, Walter Brunswick said:

    Error... Nevertheless Mr. Bethard, it is an interesting definition. However, I found that it faults when supplied a decimal or a float.

    >>> group(44.44)
    '44,.44'
    

Sign in to comment