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

1234567   ⟶   1,234,567

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


当前回答

我得到了这个工作:

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'en_US')
'en_US'
>>> locale.format("%d", 1255000, grouping=True)
'1,255,000'

当然,您不需要国际化支持,但它清晰、简洁,并使用了内置库。

附注:“%d”是通常的%样式格式化程序。您只能有一个格式化程序,但它可以是您在字段宽度和精度设置方面所需要的任何东西。

P.P.S.如果你不能在本地工作,我建议你修改一下Mark的答案:

def intWithCommas(x):
    if type(x) not in [type(0), type(0L)]:
        raise TypeError("Parameter must be an integer.")
    if x < 0:
        return '-' + intWithCommas(-x)
    result = ''
    while x >= 1000:
        x, r = divmod(x, 1000)
        result = ",%03d%s" % (r, result)
    return "%d%s" % (x, result)

递归对于否定的情况是有用的,但是每个逗号一个递归对我来说似乎有点过分了。

其他回答

下面是另一个使用生成器函数处理整数的变体:

def ncomma(num):
    def _helper(num):
        # assert isinstance(numstr, basestring)
        numstr = '%d' % num
        for ii, digit in enumerate(reversed(numstr)):
            if ii and ii % 3 == 0 and digit.isdigit():
                yield ','
            yield digit

    return ''.join(reversed([n for n in _helper(num)]))

下面是一个测试:

>>> for i in (0, 99, 999, 9999, 999999, 1000000, -1, -111, -1111, -111111, -1000000):
...     print i, ncomma(i)
... 
0 0
99 99
999 999
9999 9,999
999999 999,999
1000000 1,000,000
-1 -1
-111 -111
-1111 -1,111
-111111 -111,111
-1000000 -1,000,000

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

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)

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

稍微扩展一下Ian Schneider的回答:

如果你想使用自定义千位分隔符,最简单的解决方案是:

'{:,}'.format(value).replace(',', your_custom_thousands_separator)

例子

'{:,.2f}'.format(123456789.012345).replace(',', ' ')

如果你想要像这样的德语表示,它会变得有点复杂:

('{:,.2f}'.format(123456789.012345)
          .replace(',', ' ')  # 'save' the thousands separators 
          .replace('.', ',')  # dot to comma
          .replace(' ', '.')) # thousand separators to dot

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

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

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

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

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

浮点数:

float(filter(lambda x: x!=',', '1,234.52'))
# returns 1234.52

对于整数:

int(filter(lambda x: x!=',', '1,234'))
# returns 1234