Add 'decimal-mark' thousands separators to

2019-01-04 02:39发布

How do I format 1000000 to 1.000.000 in Python? where the '.' is the decimal-mark thousands separator.

8条回答
够拽才男人
2楼-- · 2019-01-04 03:24

Using itertools can give you some more flexibility:

>>> from itertools import zip_longest
>>> num = "1000000"
>>> sep = "."
>>> places = 3
>>> args = [iter(num[::-1])] * places
>>> sep.join("".join(x) for x in zip_longest(*args, fillvalue=""))[::-1]
'1.000.000'
查看更多
何必那么认真
3楼-- · 2019-01-04 03:30

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 higher.

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'
查看更多
登录 后发表回答