Add ‘decimal-mark’ thousands separators to a number

If you want to add a thousands separator, you can write:

>>> '{0:,}'.format(1000000)
'1,000,000'

But it only works in Python 2.7 and above.

See format string syntax.

In older versions, you can use locale.format():

>>> import locale
>>> locale.setlocale(locale.LC_ALL, '')
'en_AU.utf8'
>>> locale.format('%d', 1000000, 1)
'1,000,000'

the added benefit of using locale.format() is that it will use your locale’s thousands separator, e.g.

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'de_DE.utf-8')
'de_DE.utf-8'
>>> locale.format('%d', 1000000, 1)
'1.000.000'

Leave a Comment