对于打印带有千位分隔符的数字, 可以使用 python 格式字符串:
'{:,}'.format(1234567890)
但是我如何指定我想要千位分隔符的空格?
如果你不想搞乱,这是一个糟糕但简单的解决方案
locale
:
'{:,}'.format(1234567890.001).replace(',', ' ')
@user136036 的回答相当不错,但不幸的是它没有考虑到Python bug 的现实。完整答案如下:
如果您平台的区域设置工作正常,则只需使用区域设置:
import locale
locale.setlocale(locale.LC_ALL, '')
print("{:,d}".format(7123001))
结果取决于您的语言环境和 Python 实现是否正常工作。
但是如果根据区域设置的 Python 格式被破坏了怎么办? Linux 上的 Python 3.5?
如果 Python 不尊重
grouping=True
参数,您可以使用区域设置和解决方法(使用货币格式):
locale.setlocale(locale.LC_ALL, '')
locale._override_localeconv = {'mon_thousands_sep': '.'}
print(locale.format('%.2f', 12345.678, grouping=True, monetary=True))
上面在我的平台上给出了 12.345,68。将货币设置为 False 或忽略它 - Python 不会对数千进行分组。 指定
locale._override_localeconv = {'thousands_sep': '.'}
什么也不做。
如果您没有时间检查您平台上的 Python 哪些功能正常以及哪些功能出了问题,您可以使用常规字符串替换功能(如果您想将逗号和点交换为点和逗号):
print("{:,.2f}".format(7123001.345).replace(",", "X").replace(".", ",").replace("X", "."))
用空格替换逗号很简单(假设点是小数点分隔符):
print("{:,.2f}".format(7123001.345).replace(",", " ")
这会将语言环境设置为您的默认操作系统位置:
import locale
locale.setlocale(locale.LC_ALL, '')
然后你可以使用:
"{0:n}".format(1234567890)
print(f'{name} | Yearly salary: ${salary}.')
印刷 -> 凯特 |年薪:$60000.首先放一个 , 分隔符:
print(f'{name} | Yearly salary: ${salary:,}.')
印刷 -> 凯特 |年薪:$60,000.然后将逗号替换为空格:
print(f'{name} | Yearly salary: {salary:,} USD.'.replace(',', ' '))
印刷 -> 凯特 |年薪:60 000 美元。
注意:记住美元、美元或英镑、克朗等。符号应符合相应的通用标准
PEP 378 下定义了它,您可以看到主要提案包含 format()
函数。因此,按照该建议,我建议使用以下内容:
format(1234567890, ',d').replace(',',' ')
def format_number(string):
j = len(string) % 3
substrings = [string[3 * i + j:3 * (i + 1) + j] for i in range(len(string)//3)]
if j != 0:
substrings.insert(0, string[:j])
return " ".join(substrings)
@app.template_filter() def numberFormat(值): 返回格式(int(value), ',d').replace(',',' ')如果我在页面上显示值,则调用过滤器,如下所示:
{{ 值 |数字格式 }}
number = 1234567890
f"{number:,.2f}"