简体   繁体   English

python 带空格的格式字符串千位分隔符

[英]python format string thousand separator with spaces

For printing number with thousand separator, one can use the python format string:要打印带有千位分隔符的数字,可以使用 python 格式字符串:

'{:,}'.format(1234567890)

But how can I specify that I want a space for thousands separator?但是我怎样才能指定我想要一个千位分隔符的空间呢?

如果您不想弄乱locale这是一个糟糕但简单的解决方案:

'{:,}'.format(1234567890.001).replace(',', ' ')

Answer of @user136036 is quite good, but unfortunately it does not take into account reality of Python bugs. @user136036 的回答很好,可惜没有考虑到 Python 的 bug 的真实性。 Full answer could be following:完整的答案可能如下:

Variant A变体A

If locale of your platform is working right, then just use locale:如果您平台的语言环境正常工作,那么只需使用语言环境:

import locale
locale.setlocale(locale.LC_ALL, '')
print("{:,d}".format(7123001))

Result is dependent on your locale and Python implementation working right.结果取决于您的语言环境和 Python 实现是否正常工作。

But what if Python formatting according to locale is broken, eg Python 3.5 on Linux?但是如果根据语言环境的 Python 格式被破坏了,例如 Linux 上的 Python 3.5 呢?

Variant B变体B

If Python does not respect grouping=True parameter, you can use locale and a workaround (use monetary format):如果 Python 不尊重grouping=True参数,您可以使用语言环境和解决方法(使用货币格式):

locale.setlocale(locale.LC_ALL, '')
locale._override_localeconv = {'mon_thousands_sep': '.'}
print(locale.format('%.2f', 12345.678, grouping=True, monetary=True))

Above gives 12.345,68 on my platform.以上在我的平台上给出了 12.345,68。 Setting monetary to False or omitting it - Python does not group thousands.将货币设置为 False 或省略它 - Python 不会对数千人进行分组。 Specifying locale._override_localeconv = {'thousands_sep': '.'} do nothing.指定locale._override_localeconv = {'thousands_sep': '.'}什么都不做。

Variant C变体 C

If you don't have time to check what is working OK and what is broken with Python on your platform, you can just use regular string replace function (if you want to swap commas and dot to dots and comma):如果您没有时间检查平台上哪些工作正常以及哪些 Python 损坏,您可以使用常规字符串替换功能(如果您想将逗号和点交换为点和逗号):

print("{:,.2f}".format(7123001.345).replace(",", "X").replace(".", ",").replace("X", "."))

Replacing comma for space is trivial (point is assumed decimal separator):用逗号代替空格很简单(点被假定为十进制分隔符):

print("{:,.2f}".format(7123001.345).replace(",", " ")

This will set the locale environment to your default OS location:这会将语言环境设置为您的默认操作系统位置:

import locale
locale.setlocale(locale.LC_ALL, '')

Then you can use:然后你可以使用:

"{0:n}".format(1234567890)

You'll have to use the 'n' locale-aware number format instead, and set your locale to one that uses a space as a thousands separator.您必须改用'n'区域设置感知数字格式,并将 您的区域设置设置为使用空格作为千​​位分隔符的 区域设置 Yes, this is painful.是的,这很痛苦。

'n' - Number. 'n' - 数字。 This is the same as 'd' , except that it uses the current locale setting to insert the appropriate number separator characters.这与'd'相同,不同之处在于它使用当前区域设置来插入适当的数字分隔符。

If you don't want to use the local, a solution that works with every size of string :如果您不想使用本地,一个适用于所有字符串大小的解决方案:

    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)

Python community has it defined under PEP 378 , where you can see that the main proposal includes format() function. Python 社区在PEP 378下对其进行了定义,您可以在其中看到主要提案包括format()函数。 So, by following that proposal, I suggest using the following:因此,通过遵循该建议,我建议使用以下内容:

format(1234567890, ',d').replace(',',' ')

Lets say you code:假设你编码:

print(f'{name} | Yearly salary: ${salary}.')

PRINTS -> Kate |打印 -> 凯特 | Yearly salary: $60000.年薪:60000美元。

First put a , separator:首先放一个 , 分隔符:

print(f'{name} | Yearly salary: ${salary:,}.')

PRINTS -> Kate |打印 -> 凯特 | Yearly salary: $60,000.年薪:60,000美元。

Then replace the comma with a space:然后用空格替换逗号:

print(f'{name} | Yearly salary: {salary:,} USD.'.replace(',', ' '))

PRINTS -> Kate |打印 -> 凯特 | Yearly salary: 60 000 USD.年薪:60 000 美元。

NB: Remember USD, $ or £, kroner etc. notation should match accordingly universal standards注意:记住美元、美元或英镑、克朗等符号应相应地符合通用标准

You can use an f-string:您可以使用 f 字符串:

number = 1234567890
f"{number:,.2f}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM