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

1234567   ⟶   1,234,567

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


当前回答

Python 2.5+和Python 3(仅限正int):

''.join(reversed([x + (',' if i and not i % 3 else '') for i, x in enumerate(reversed(str(1234567)))]))

其他回答

我相信这一定有一个标准的库函数,但尝试自己用递归写它很有趣,所以这是我想到的:

def intToStringWithCommas(x):
    if type(x) is not int and type(x) is not long:
        raise TypeError("Not an integer!")
    if x < 0:
        return '-' + intToStringWithCommas(-x)
    elif x < 1000:
        return str(x)
    else:
        return intToStringWithCommas(x / 1000) + ',' + '%03d' % (x % 1000)

话虽如此,如果其他人确实找到了一种标准的方法,那么您应该使用它。

接受的答案是好的,但我实际上更喜欢格式(数字,',')。对我来说更容易理解和记忆。

https://docs.python.org/3/library/functions.html#format

你也可以使用'{:n}'。区域设置表示的格式(值)。我认为这是最简单的现场解决方案。

有关更多信息,请在Python DOC中搜索数千个。

对于货币,可以使用locale。货币,设置标志分组:

Code

import locale

locale.setlocale( locale.LC_ALL, '' )
locale.currency( 1234567.89, grouping = True )

输出

'Portuguese_Brazil.1252'
'R$ 1.234.567,89'

意大利:

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

通用解决方案

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

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