2013-07-05 66 views
5

如何使用十进制数字简单格式化字符串以显示每三位数字之间的空格?格式化字符串 - 每三位数字之间的空格

我可以做这样的事情:

some_result = '12345678,46' 
' '.join(re.findall('...?', test[:test.find(',')]))+test[test.find(','):] 

和结果是:

'123 456 78,46' 

,但我想:

'12 345 678,46' 
+0

什么''12345678,46123''? –

+0

@ AshwiniChaudhary:通常,人们不会在小数点后放置数千个分隔符。至少PEP 378格式化不能,我也不能挖掘任何LC_NUMERIC。 – abarnert

+1

尝试从'end'开始空格而不是从开头 – Zaffy

回答

14

这是一个有点哈克,但:

format(12345678.46, ',').replace(',', ' ').replace('.', ',') 

Format specification mini-language描述的,在一个format_spec:

的“”选项用信号通知使用的千隔板的逗号。

然后我们用逗号替换每个逗号,然后用逗号替换小数点,我们就完成了。

对于使用str.format代替format更复杂的情况下,format_spec进入结肠后,如:

'{:,}'.format(12345678.46) 

详见PEP 378


同时,如果你只是想使用标准的分组,分离器系统的语言环境,有更容易的方式来做到这一点,在n格式类型,或locale.format功能等。例如:

>>> locale.setlocale(locale.LC_NUMERIC, 'pl_PL') 
>>> format(12345678, 'n') 
12 345 678 
>>> locale.format('%.2f' 12345678.12, grouping=True) 
12 345 678,46 
>>> locale.setlocale(locale.LC_NUMERIC, 'fr_FR') 
>>> locale.format('%.2f' 12345678.12, grouping=True) 
12345678,46 
>>> locale.setlocale(locale.LC_ALL, 'en_AU') 
>>> locale.format('%.2f' 12345678.12, grouping=True) 
12,345,678.46 

如果您的系统语言环境是,说,pl_PL,只是打电话locale.setlocale(locale.LC_NUMERIC)(或locale.setlocale(locale.LC_ALL))将拿起你想要的波兰设置,但在澳大利亚的运行程序是同一人会拿起澳大利亚设置,他要。

1

用途:

' '.join(re.findall('...?',test[:test.find(',')][::-1]))[::-1]+test[test.find(','):] 

您已经使用正则表达式,其开始从匹配的开始的字符串。但是,您想将末尾(逗号前)的3个数字分组。

因此,在逗号前反转字符串,应用相同的逻辑,然后将其逆转回去。

5

我认为,正则表达式将会更加美好:

>>> import re 
>>> some_result = '12345678,46' 
>>> re.sub(r"\B(?=(?:\d{3})+,)", " ", some_result) 
'12 345 678,46' 

说明:

\B  # Assert that we're not at the start of a number 
(?=  # Assert that the following regex could match from here: 
(?:  # The following non-capturing group 
    \d{3} # which contains three digits 
)+  # and can be matched one or more times 
,  # until a comma follows. 
)  # End of lookahead assertion 
+0

+1提供正则表达式的细分! – Christoph