Thousands separator provides a clearer way to see the order of a number is. In Python, it can be added with format specifier as seen below.
1 Using str.format
With str.format, format specifier for thousands separator is support by PEP 378, for example:
>>> '{:15,f}'.format(54321.123) ' 54,321.123000'
1.1 Different separator
In different locale or usages, there may be needs to format with the separator other than commas. In PEP 378, it provides some examples.
Periods for thousands separator and comma as decimal point:
>>> '{:15,f}'.format(54321.123).replace(",", "X").replace(".", ",").replace("X", ".") ' 54.321,123000'
Or spaces for thousands separator:
>>> '{:15,f}'.format(54321.123).replace(",", " ") ' 54 321.123000'
2 Using locale
If str.format isnt available as the Python is older than 2.6, then you can use locale, for example:
import locale locale.setlocale(locale.LC_ALL, 'en_US') print locale.format("%d", 7654321, grouping=True) print locale.format("%f", 7654321.12345, grouping=True)
But this method relies on what locale is available on the system, its more likely to be an issue when running a script in different system since not all systems are built the same.
3 Using intcomma
Or write own code:
def intcomma(n): sign = '-' if n < 0 else '' n = str(abs(n)).split('.') dec = '' if len(n) == 1 else '.' + n[1] # A) # n = ' '*(3-len(n[0])%3) + n[0] # return sign + (','.join([n[i*3:(i+1)*3] for i in range(len(n)/3)])).lstrip(' ,') + dec # B) n = n[0] m = len(n) # B-1) # return sign + ','.join(filter(None, [n[0:m%3]] + [n[i:i+3] for i in range(m%3, m, 3)])) + dec # B-2) return sign + (','.join([n[0:m%3]] + [n[i:i+3] for i in range(m%3, m, 3)])).lstrip(',') + dec
Its named after intcomma filter from Djangos humanize. The method A prepends spaces so the string format of the number will be len(n)%3 == 0. The method B-1 and B-2 use different way to extract part of number (the part before first thousands separator), then take 3 digits after each time. By the way, in method A, I finally have one reasonable usage of str.lstrip([chars]). Note that there is a reason why Python doc uses [chars] not str_to_strip.
A quick test:
print intcomma(0) print intcomma(1) print intcomma(21) print intcomma(321) print intcomma(4321) print intcomma(54321) print intcomma(654321) print intcomma(7654321) print print intcomma(4321.1234) print print intcomma(-0) print intcomma(-1) print intcomma(-21) print intcomma(-321) print intcomma(-4321) print intcomma(-54321) print intcomma(-654321) print intcomma(-7654321) print print intcomma(-4321.1234) print 0 1 21 321 4,321 54,321 654,321 7,654,321 4,321.1234 0 -1 -21 -321 -4,321 -54,321 -654,321 -7,654,321 -4,321.1234
4 Changes
- 2013-07-28T06:30:30Z: add builtin format specifier.