我如何打印一个整数与逗号作为千分隔符?

1234567   ⟶   1,234,567

在句点和逗号之间决定不需要特定于区域设置。


当前回答

意大利:

>>> import locale
>>> locale.setlocale(locale.LC_ALL,"")
'Italian_Italy.1252'
>>> f"{1000:n}"
'1.000'

其他回答

这是烘焙到python per PEP -> https://www.python.org/dev/peps/pep-0378/

只需使用format(1000, ',d')来显示一个带千位分隔符的整数

PEP中描述了更多的格式,请尝试一下

从评论到activestate recipe 498181,我重做了这个:

import re
def thous(x, sep=',', dot='.'):
    num, _, frac = str(x).partition(dot)
    num = re.sub(r'(\d{3})(?=\d)', r'\1'+sep, num[::-1])[::-1]
    if frac:
        num += dot + frac
    return num

它使用正则表达式特性:超前,即(?=\d)来确保只有三个数字组成的“后面”有一个数字的组才会有逗号。我说'after'是因为在这一点上字符串是反向的。

[::-1]只是反转一个字符串。

这是我处理浮点数的方法。尽管,老实说,我不确定它适用于哪个版本——我使用的是2.7:

my_number = 4385893.382939491

my_string = '{:0,.2f}'.format(my_number)

返回:4385893 .38点

更新:我最近有一个关于这种格式的问题(不能告诉你确切的原因),但能够通过删除0来修复它:

my_string = '{:,.2f}'.format(my_number)

通用解决方案

我在以前投票最多的答案中发现了点分隔符的一些问题。我已经设计了一个通用的解决方案,您可以使用任何您想要作为千个分隔符,而无需修改区域设置。我知道这不是最优雅的解决方案,但它完成了工作。请随意改进它!

def format_integer(number, thousand_separator='.'):
    def reverse(string):
        string = "".join(reversed(string))
        return string

    s = reverse(str(number))
    count = 0
    result = ''
    for char in s:
        count = count + 1
        if count % 3 == 0:
            if len(s) == count:
                result = char + result
            else:
                result = thousand_separator + char + result
        else:
            result = char + result
    return result


print(format_integer(50))
# 50
print(format_integer(500))
# 500
print(format_integer(50000))
# 50.000
print(format_integer(50000000))
# 50.000.000

当地unaware

'{:,}'.format(value)  # For Python ≥2.7
f'{value:,}'          # For Python ≥3.6

区域设置感知

import locale
locale.setlocale(locale.LC_ALL, '')  # Use '' for auto, or force e.g. to 'en_US.UTF-8'

'{:n}'.format(value)  # For Python ≥2.7
f'{value:n}'          # For Python ≥3.6

参考

根据格式规范迷你语言,

','选项表示使用逗号作为千位分隔符。对于支持区域设置的分隔符,请使用'n'整数表示类型。