What the title says. No more, no less. (Version 2, now supports negative numbers.)
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'
Note that the locale module does most of what you want here:
Error... Nevertheless Mr. Bethard, it is an interesting definition. However, I found that it faults when supplied a decimal or a float.
Here's my solution to the problem. It's designed to work for any real number.