我如何打印一个整数与逗号作为千分隔符?
1234567 ⟶ 1,234,567
在句点和逗号之间决定不需要特定于区域设置。
我如何打印一个整数与逗号作为千分隔符?
1234567 ⟶ 1,234,567
在句点和逗号之间决定不需要特定于区域设置。
当前回答
你也可以使用'{:n}'。区域设置表示的格式(值)。我认为这是最简单的现场解决方案。
有关更多信息,请在Python DOC中搜索数千个。
对于货币,可以使用locale。货币,设置标志分组:
Code
import locale
locale.setlocale( locale.LC_ALL, '' )
locale.currency( 1234567.89, grouping = True )
输出
'Portuguese_Brazil.1252'
'R$ 1.234.567,89'
其他回答
简单的回答是:
format (123456, ",")
结果:
'123,456'
稍微扩展一下Ian Schneider的回答:
如果你想使用自定义千位分隔符,最简单的解决方案是:
'{:,}'.format(value).replace(',', your_custom_thousands_separator)
例子
'{:,.2f}'.format(123456789.012345).replace(',', ' ')
如果你想要像这样的德语表示,它会变得有点复杂:
('{:,.2f}'.format(123456789.012345)
.replace(',', ' ') # 'save' the thousands separators
.replace('.', ',') # dot to comma
.replace(' ', '.')) # thousand separators to dot
你也可以使用'{:n}'。区域设置表示的格式(值)。我认为这是最简单的现场解决方案。
有关更多信息,请在Python DOC中搜索数千个。
对于货币,可以使用locale。货币,设置标志分组:
Code
import locale
locale.setlocale( locale.LC_ALL, '' )
locale.currency( 1234567.89, grouping = True )
输出
'Portuguese_Brazil.1252'
'R$ 1.234.567,89'
Python 2.5+和Python 3(仅限正int):
''.join(reversed([x + (',' if i and not i % 3 else '') for i, x in enumerate(reversed(str(1234567)))]))
下面是另一个使用生成器函数处理整数的变体:
def ncomma(num):
def _helper(num):
# assert isinstance(numstr, basestring)
numstr = '%d' % num
for ii, digit in enumerate(reversed(numstr)):
if ii and ii % 3 == 0 and digit.isdigit():
yield ','
yield digit
return ''.join(reversed([n for n in _helper(num)]))
下面是一个测试:
>>> for i in (0, 99, 999, 9999, 999999, 1000000, -1, -111, -1111, -111111, -1000000):
... print i, ncomma(i)
...
0 0
99 99
999 999
9999 9,999
999999 999,999
1000000 1,000,000
-1 -1
-111 -111
-1111 -1,111
-111111 -111,111
-1000000 -1,000,000