如何打印带有数千个分隔符的浮子?

yit*_*al9 13 python format decimal

如何格式化十进制数以便32757121.33显示为32.757.121,33

Tim*_*ker 17

用途locale.format():

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'German')
'German_Germany.1252'
>>> print(locale.format('%.2f', 32757121.33, True))
32.757.121,33
Run Code Online (Sandbox Code Playgroud)

您可以将区域设置更改限制为显示数值(使用locale.format()locale.str()等),并保持其他区域设置不受影响:

>>> locale.setlocale(locale.LC_NUMERIC, 'English')
'English_United States.1252'
>>> print(locale.format('%.2f', 32757121.33, True))
32,757,121.33
>>> locale.setlocale(locale.LC_NUMERIC, 'German')
'German_Germany.1252'
>>> print(locale.format('%.2f', 32757121.33, True))
32.757.121,33
Run Code Online (Sandbox Code Playgroud)

  • 由于这些调用的额外麻烦取决于操作系统可用的语言环境-此外,语言环境名称在不同的OS甚至不同的Linux发行版上都会有所不同(这意味着您必须在生产服务器上进行测试,或者拥有提供后备功能的代码,直到它查找现有语言环境) (2认同)

yit*_*al9 12

我找到了另一个解决方案:

'{:,.2f}'.format(num).replace(".","%").replace(",",".").replace("%",",")
Run Code Online (Sandbox Code Playgroud)

  • 这在 `...(num)` 之后没有任何废话 (4认同)
  • 可怕的解决方案。如果这在成千上万的任意长度的字符串上被调用怎么办? (2认同)

Tim*_*ker 5

如果locale由于某种原因你不能或不想使用,你也可以使用正则表达式:

import re
def sep(s, thou=",", dec="."):
    integer, decimal = s.split(".")
    integer = re.sub(r"\B(?=(?:\d{3})+$)", thou, integer)
    return integer + dec + decimal
Run Code Online (Sandbox Code Playgroud)

sep() 获取标准Python float的字符串表示形式,并使用自定义千位和小数分隔符返回它.

>>> s = "%.2f" % 32757121.33
>>> sep(s)
'32,757,121.33'
>>> sep(s, thou=".", dec=",")
'32.757.121,33'
Run Code Online (Sandbox Code Playgroud)

说明:

\B      # Assert that we're not at the start of the number
(?=     # Match at a position where it's possible to match...
 (?:    #  the following regex:
  \d{3} #   3 digits
 )+     #  repeated at least once
 $      #  until the end of the string
)       # (thereby ensuring a number of digits divisible by 3
Run Code Online (Sandbox Code Playgroud)