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

1234567   ⟶   1,234,567

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


当前回答

只是long的子类(或者float,等等)。这是非常实用的,因为通过这种方式,您仍然可以在数学操作中使用您的数字(因此也可以使用现有的代码),但它们都将在终端中很好地打印出来。

>>> class number(long):

        def __init__(self, value):
            self = value

        def __repr__(self):
            s = str(self)
            l = [x for x in s if x in '1234567890']
            for x in reversed(range(len(s)-1)[::3]):
                l.insert(-x, ',')
            l = ''.join(l[1:])
            return ('-'+l if self < 0 else l) 

>>> number(-100000)
-100,000
>>> number(-100)
-100
>>> number(-12345)
-12,345
>>> number(928374)
928,374
>>> 345

其他回答

我很惊讶,没有人提到你可以在Python 3.6+中使用f-strings做到这一点,就像这样简单:

>>> num = 10000000
>>> print(f"{num:,}")
10,000,000

... 冒号后面的部分是格式说明符。逗号是您想要的分隔符,因此f"{num:_}"使用下划线而不是逗号。此方法只能使用“,”和“_”。

这相当于在旧版本的python 3中使用format(num, ",")。

当你第一次看到它时,它可能看起来像魔法,但它不是。它只是语言的一部分,通常需要有一个可用的快捷方式。要了解更多信息,请查看group子组件。

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

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)

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

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

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

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

my_number = 4385893.382939491

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

返回:4385893 .38点

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

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

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

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