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

1234567   ⟶   1,234,567

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


当前回答

简单的回答是:

format (123456, ",")

结果:

'123,456'

其他回答

下面是移除不相关部分并稍微清理后的地区分组代码:

(以下仅适用于整数)

def group(number):
    s = '%d' % number
    groups = []
    while s and s[-1].isdigit():
        groups.append(s[-3:])
        s = s[:-3]
    return s + ','.join(reversed(groups))

>>> group(-23432432434.34)
'-23,432,432,434'

这里已经有一些很好的答案了。我只是想补充一下,以备将来参考。在python 2.7中,将有一个用于千位分隔符的格式说明符。根据python文档,它是这样工作的

>>> '{:20,.2f}'.format(f)
'18,446,744,073,709,551,616.00'

在python3.1中,你可以这样做:

>>> format(1234567, ',d')
'1,234,567'

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

my_number = 4385893.382939491

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

返回:4385893 .38点

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

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

下面是一行正则表达式替换:

re.sub("(\d)(?=(\d{3})+(?!\d))", r"\1,", "%d" % val)

仅适用于积分输出:

import re
val = 1234567890
re.sub("(\d)(?=(\d{3})+(?!\d))", r"\1,", "%d" % val)
# Returns: '1,234,567,890'

val = 1234567890.1234567890
# Returns: '1,234,567,890'

或者对于小于4位的浮点数,将格式说明符更改为%.3f:

re.sub("(\d)(?=(\d{3})+(?!\d))", r"\1,", "%.3f" % val)
# Returns: '1,234,567,890.123'

注意:不能正确工作与超过三个十进制数字,因为它将尝试分组小数部分:

re.sub("(\d)(?=(\d{3})+(?!\d))", r"\1,", "%.5f" % val)
# Returns: '1,234,567,890.12,346'

它是如何工作的

让我们来分析一下:

re.sub(pattern, repl, string)

pattern = \
    "(\d)           # Find one digit...
     (?=            # that is followed by...
         (\d{3})+   # one or more groups of three digits...
         (?!\d)     # which are not followed by any more digits.
     )",

repl = \
    r"\1,",         # Replace that one digit by itself, followed by a comma,
                    # and continue looking for more matches later in the string.
                    # (re.sub() replaces all matches it finds in the input)

string = \
    "%d" % val      # Format the string as a decimal to begin with

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

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

只是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