python format string thousand separator with spaces

落花浮王杯 提交于 2019-11-28 06:42:13

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!