Python将逗号添加到数字字符串中

The*_*Woo 39 python string

使用Python v2,我有一个运行在我的程序中的值,它在最后输出一个舍入到2位小数的数字:

像这样:

print ("Total cost is: ${:0.2f}".format(TotalAmount))
Run Code Online (Sandbox Code Playgroud)

有没有办法在小数点左边每3位数插入一个逗号值?

即:10000.00变为10,000.00或1000000.00变为1,000,000.00

谢谢你的帮助.

Sve*_*ach 69

在Python 2.7或更高版本中,您可以使用

print ("Total cost is: ${:,.2f}".format(TotalAmount))
Run Code Online (Sandbox Code Playgroud)

这在PEP 378中有记载.

(从您的代码中,我无法分辨您正在使用哪个Python版本.)

  • @AA:99%的SO用户来自谷歌.@The Woo是否做了他的作业并不重要(尽管这个问题应该被标记为(如果是这样)以适当地策划答案).它不是IRC,您首先帮助个人并回答第二个问题(不同的焦点). (12认同)

T H*_*T H 16

另一种很短的方法是

value = -122212123.12
print(f"{value:,}")
Run Code Online (Sandbox Code Playgroud)

  • F 弦的现代答案。 (2认同)

jfs*_*jfs 15

你可以使用locale.currencyif TotalAmount代表钱.它也适用于Python <2.7:

>>> locale.setlocale(locale.LC_ALL, '')
'en_US.utf8'
>>> locale.currency(123456.789, symbol=False, grouping=True)
'123,456.79'
Run Code Online (Sandbox Code Playgroud)

注意:它不适用于C语言环境,因此您应该在调用之前设置其他语言环境.


小智 12

如果你使用的是Python 3或更高版本,这里有一个更简单的插入逗号的方法:

第一种方式

value = -12345672
print (format (value, ',d'))
Run Code Online (Sandbox Code Playgroud)

或另一种方式

value = -12345672
print ('{:,}'.format(value)) 
Run Code Online (Sandbox Code Playgroud)

  • 这些值可能是浮点数,而不是整数,所以它是“format(value, ",f")” (2认同)

Pet*_*lly 8

'{:20,.2f}'.format(TotalAmount)
Run Code Online (Sandbox Code Playgroud)


ThR*_*R37 6

这不是特别优雅,但也应该工作:

a = "1000000.00"
e = list(a.split(".")[0])
for i in range(len(e))[::-3][1:]:
    e.insert(i+1,",")
result = "".join(e)+"."+a.split(".")[1]
Run Code Online (Sandbox Code Playgroud)


dna*_*an7 5

在 python2.7+ 或 python3.1+ 中工作的函数

def comma(num):
    '''Add comma to every 3rd digit. Takes int or float and
    returns string.'''
    if type(num) == int:
        return '{:,}'.format(num)
    elif type(num) == float:
        return '{:,.2f}'.format(num) # Rounds to 2 decimal places
    else:
        print("Need int or float as input to function comma()!")
Run Code Online (Sandbox Code Playgroud)