2013-07-05 69 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