58

如何在 Python 中格式化1000000为?1.000.000'.' 在哪里 是小数点千位分隔符。

4

9 回答 9

116

如果要添加千位分隔符,可以编写:

>>> '{0:,}'.format(1000000)
'1,000,000'

但它只适用于 Python 2.7 及更高版本。

请参阅格式字符串语法

在旧版本中,您可以使用locale.format()

>>> import locale
>>> locale.setlocale(locale.LC_ALL, '')
'en_AU.utf8'
>>> locale.format('%d', 1000000, 1)
'1,000,000'

使用的额外好处locale.format()是它将使用您的语言环境的千位分隔符,例如

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'de_DE.utf-8')
'de_DE.utf-8'
>>> locale.format('%d', 1000000, 1)
'1.000.000'
于 2011-04-01T13:02:09.467 回答
20

我真的不明白。但这是我的理解:

您想将 1123000 转换为 1,123,000。您可以通过使用格式来做到这一点:

http://docs.python.org/release/3.1.3/whatsnew/3.1.html#pep-378-format-specifier-for-thousands-separator

例子:

>>> format(1123000,',d')
'1,123,000'
于 2011-04-01T12:56:58.763 回答
19

在这里稍微扩展一下答案:)

我需要有千分之一的分隔符并限制浮点数的精度。

这可以通过使用以下格式字符串来实现:

> my_float = 123456789.123456789
> "{:0,.2f}".format(my_float)
'123,456,789.12'

这描述了format()-specifier 的迷你语言:

[[fill]align][sign][#][0][width][,][.precision][type]

来源:https ://www.python.org/dev/peps/pep-0378/#current-version-of-the-mini-language

于 2015-09-25T08:06:11.000 回答
6

一个想法

def itanum(x):
    return format(x,',d').replace(",",".")

>>> itanum(1000)
'1.000'
于 2018-11-18T17:39:34.320 回答
1

使用itertools可以给你更多的灵活性:

>>> from itertools import zip_longest
>>> num = "1000000"
>>> sep = "."
>>> places = 3
>>> args = [iter(num[::-1])] * places
>>> sep.join("".join(x) for x in zip_longest(*args, fillvalue=""))[::-1]
'1.000.000'
于 2016-07-05T08:49:04.580 回答
1

根据 Mikel 的答案,我在我的 matplotlib 图中实现了他的解决方案。我想有些人可能会觉得它有帮助:

ax=plt.gca()
ax.get_xaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, loc: locale.format('%d', x, 1)))
于 2018-01-18T13:52:05.630 回答
1

奇怪的是,没有人提到使用正则表达式的简单解决方案:

import re
print(re.sub(r'(?<!^)(?=(\d{3})+$)', r'.', "12345673456456456"))

给出以下输出:

12.345.673.456.456.456

如果您只想在逗号之前分隔数字,它也可以:

re.sub(r'(?<!^)(?=(\d{3})+,)', r'.', "123456734,56456456")

给出:

123.456.734,56456456

正则表达式使用前瞻来检查给定位置之后的位数是否可被 3 整除。


2021 年更新:请仅将其用于脚本(即仅在使用后可以销毁代码的情况下)。在应用程序中使用时,这种方法将构成ReDoS

于 2018-04-17T01:31:48.510 回答
0

这只是一个替代答案。您可以在 python 中使用 split 运算符并通过一些奇怪的逻辑这是代码

i=1234567890
s=str(i)
str1=""
s1=[elm for elm in s]
if len(s1)%3==0:
    for i in range(0,len(s1)-3,3):
        str1+=s1[i]+s1[i+1]+s1[i+2]+"."
    str1+=s1[i]+s1[i+1]+s1[i+2]
else:
    rem=len(s1)%3
    for i in range(rem):
        str1+=s1[i]
    for i in range(rem,len(s1)-1,3):
        str1+="."+s1[i]+s1[i+1]+s1[i+2]

print str1

输出

1.234.567.890
于 2016-07-05T10:54:20.007 回答
0

DIY解决方案

def format_number(n):
    result = ""
    for i, digit in enumerate(reversed(str(n))):
        if i != 0 and (i % 3) == 0:
            result += ","
        result += digit
    return result[::-1]

内置解决方案

def format_number(n):
    return "{:,}".format(n)
于 2022-01-12T07:38:44.527 回答