如何简单地格式化带有十进制数字的字符串,以显示每三位数之间的空格?
我可以做这样的事情:
some_result = '12345678,46'
' '.join(re.findall('...?', test[:test.find(',')]))+test[test.find(','):]
Run Code Online (Sandbox Code Playgroud)
结果是:
'123 456 78,46'
Run Code Online (Sandbox Code Playgroud)
但我想要:
'12 345 678,46'
Run Code Online (Sandbox Code Playgroud)
aba*_*ert 14
这有点hacky,但是:
format(12345678.46, ',').replace(',', ' ').replace('.', ',')
Run Code Online (Sandbox Code Playgroud)
','选项表示使用逗号分隔千位分隔符.
然后我们用空格替换每个逗号,然后用逗号替换小数点,我们就完成了.
对于使用str.format而不是使用的更复杂的情况format,format_spec在冒号后面,如:
'{:,}'.format(12345678.46)
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅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
Run Code Online (Sandbox Code Playgroud)
如果您的系统语言环境,比如pl_PL,只调用locale.setlocale(locale.LC_NUMERIC)(或locale.setlocale(locale.LC_ALL))将拿起你想要的波兰设置,但在澳大利亚的运行程序是同一个人将拿起他希望澳大利亚设置.
我认为正则表达式会更好:
>>> import re
>>> some_result = '12345678,46'
>>> re.sub(r"\B(?=(?:\d{3})+,)", " ", some_result)
'12 345 678,46'
Run Code Online (Sandbox Code Playgroud)
说明:
\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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2532 次 |
| 最近记录: |