Welcome, guest | Sign In | My Account | Store | Cart

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

Python, 12 lines
 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

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'

3 comments

Steven Bethard 18 years, 8 months ago  # | flag

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'
Walter Brunswick 18 years, 7 months ago  # | flag

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'
Phil Huffman 12 years, 9 months ago  # | flag

Here's my solution to the problem. It's designed to work for any real number.

def group_digits(number = 0, separator = ',', group_size = 3):
   
if (number < 0):
        prefix
= '-'
        number
= -number;
   
else:
        prefix
= ''
   
string = "{0}".format(number)
    dot_index
= string.find('.');
    string_size
= len(string) if dot_index == -1 else dot_index

   
if string_size > group_size:
        groups
= []
        first_group_size
= string_size % group_size;
       
if first_group_size:
            groups
.append(string[0:first_group_size])
       
for i in range(first_group_size, string_size, group_size):
            groups
.append(string[i:i+group_size])
        return_string
= separator.join(groups)
       return_string
= return_string if dot_index == -1 else return_string + string[dot_index:]
   
else:
        return_string
= string

   
return prefix + return_string
Created by Marek Baczynski on Wed, 17 Aug 2005 (PSF)
Python recipes (4591)
Marek Baczynski's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks