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

1234567   ⟶   1,234,567

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


当前回答

当地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'整数表示类型。

其他回答

这里有一个也适用于浮动:

def float2comma(f):
    s = str(abs(f)) # Convert to a string
    decimalposition = s.find(".") # Look for decimal point
    if decimalposition == -1:
        decimalposition = len(s) # If no decimal, then just work from the end
    out = "" 
    for i in range(decimalposition+1, len(s)): # do the decimal
        if not (i-decimalposition-1) % 3 and i-decimalposition-1: out = out+","
        out = out+s[i]      
    if len(out):
        out = "."+out # add the decimal point if necessary
    for i in range(decimalposition-1,-1,-1): # working backwards from decimal point
        if not (decimalposition-i-1) % 3 and decimalposition-i-1: out = ","+out
        out = s[i]+out      
    if f < 0:
        out = "-"+out
    return out

使用的例子:

>>> float2comma(10000.1111)
'10,000.111,1'
>>> float2comma(656565.122)
'656,565.122'
>>> float2comma(-656565.122)
'-656,565.122'

我有这个代码的python 2和python 3版本。我知道这个问题是关于python2的,但是现在(8年过去了,哈哈)人们可能会使用python3。Python 3代码:

import random
number = str(random.randint(1, 10000000))
comma_placement = 4
print('The original number is: {}. '.format(number))
while True:
    if len(number) % 3 == 0:
        for i in range(0, len(number) // 3 - 1):
            number = number[0:len(number) - comma_placement + 1] + ',' + number[len(number) - comma_placement + 1:]
            comma_placement = comma_placement + 4
    else:
        for i in range(0, len(number) // 3):
            number = number[0:len(number) - comma_placement + 1] + ',' + number[len(number) - comma_placement + 1:]
    break
print('The new and improved number is: {}'.format(number))        

Python 2代码:(编辑。python代码不能工作。我认为语法是不同的)。

import random
number = str(random.randint(1, 10000000))
comma_placement = 4
print 'The original number is: %s.' % (number)
while True:
    if len(number) % 3 == 0:
        for i in range(0, len(number) // 3 - 1):
            number = number[0:len(number) - comma_placement + 1] + ',' + number[len(number) - comma_placement + 1:]
            comma_placement = comma_placement + 4
    else:
        for i in range(0, len(number) // 3):
            number = number[0:len(number) - comma_placement + 1] + ',' + number[len(number) - comma_placement + 1:]
    break
print 'The new and improved number is: %s.' % (number) 

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

(以下仅适用于整数)

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'

从评论到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]只是反转一个字符串。

下面是一些格式化的方法(与float和int类型兼容)

num = 2437.68

# Way 1: String Formatting

'{:,}'.format(num)
>>> '2,437.68'


# Way 2: F-Strings

f'{num:,}'
>>> '2,437.68'


# Way 3: Built-in Format Function

format(num, ',')
>>> '2,437.68'