python format string thousand separator with spaces

For printing number with thousand separator, one can use the python format string :

'{:,}'.format(1234567890)

But how can I specify that I want a space for thousands separator?


Here is bad but simple solution if you don't want to mess with locale:

'{:,}'.format(1234567890.001).replace(',', ' ')

Answer of @user136036 is quite good, but unfortunately it does not take into account reality of Python bugs. Full answer could be following:

Variant A

If locale of your platform is working right, then just use locale:

import locale
locale.setlocale(locale.LC_ALL, '')
print("{:,d}".format(7123001))

Result is dependent on your locale and Python implementation working right.

But what if Python formatting according to locale is broken, e.g. Python 3.5 on Linux?

Variant B

If Python does not respect grouping=True parameter, you can use locale and a workaround (use monetary format):

locale.setlocale(locale.LC_ALL, '')
locale._override_localeconv = {'mon_thousands_sep': '.'}
print(locale.format('%.2f', 12345.678, grouping=True, monetary=True))

Above gives 12.345,68 on my platform. Setting monetary to False or omitting it - Python does not group thousands. Specifying locale._override_localeconv = {'thousands_sep': '.'} do nothing.

Variant C

If you don't have time to check what is working OK and what is broken with Python on your platform, you can just use regular string replace function (if you want to swap commas and dot to dots and comma):

print("{:,.2f}".format(7123001.345).replace(",", "X").replace(".", ",").replace("X", "."))

Replacing comma for space is trivial (point is assumed decimal separator):

print("{:,.2f}".format(7123001.345).replace(",", " ")


This will set the locale environment to your default OS location:

import locale
locale.setlocale(locale.LC_ALL, '')

Then you can use:

"{0:n}".format(1234567890)

You'll have to use the 'n' locale-aware number format instead, and set your locale to one that uses a space as a thousands separator. Yes, this is painful.

'n' - Number. This is the same as 'd', except that it uses the current locale setting to insert the appropriate number separator characters.