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

问题描述 投票:34回答:8

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

像这样:

print ("Total cost is: ${:0.2f}".format(TotalAmount))

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

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

谢谢你的帮助。

python string
8个回答
64
投票

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

print ("Total cost is: ${:,.2f}".format(TotalAmount))

这在PEP 378中有记载。

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


15
投票

如果locale.currency代表钱,你可以使用TotalAmount。它也适用于Python <2.7:

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

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


11
投票

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

First way

value = -12345672
print (format (value, ',d'))

or another way

value = -12345672
print ('{:,}'.format(value)) 

4
投票
'{:20,.2f}'.format(TotalAmount)

4
投票

一个在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()!")

3
投票

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

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]

0
投票

上面的答案比我在我的(非家庭作业)项目中使用的代码要好得多:

def commaize(number):
    text = str(number)
    parts = text.split(".")
    ret = ""
    if len(parts) > 1:
        ret = "."
        ret += parts[1] # Apparently commas aren't used to the right of the decimal point
    # The -1 offsets to len() and 0 are because len() is 1 based but text[] is 0 based
    for i in range(len(parts[0]) - 1,-1,-1):
        # We can't just check (i % 3) because we're counting from right to left
        #  and i is counting from left to right. We can overcome this by checking
        #  len() - i, although it needs to be adjusted for the off-by-one with a -1
        # We also make sure we aren't at the far-right (len() - 1) so we don't end
        #  with a comma
        if (len(parts[0]) - i - 1) % 3 == 0 and i != len(parts[0]) - 1:
            ret = "," + ret
        ret = parts[0][i] + ret
    return ret

0
投票

大约5个小时前开始学习Python,但我想我想出了一些整数的东西(对不起,无法弄清楚花车)。我上高中,代码可能更有效率;我刚刚从头开始做了一些对我有意义的事情。如果有人对如何改进以及它如何工作的充分解释有任何想法,请告诉我!

# Inserts comma separators
def place_value(num):
    perm_num = num  # Stores "num" to ensure it cannot be modified
    lis_num = list(str(num))  # Makes "num" into a list of single-character strings since lists are easier to manipulate
    if len(str(perm_num)) > 3:
        index_offset = 0  # Every time a comma is added, the numbers are all shifted over one
        for index in range(len(str(perm_num))):  # Converts "perm_num" to string so len() can count the length, then uses that for a range
            mod_index = (index + 1) % 3  # Locates every 3 index
            neg_index = -1 * (index + 1 + index_offset)  # Calculates the index that the comma will be inserted at
            if mod_index == 0:  # If "index" is evenly divisible by 3
                lis_num.insert(neg_index, ",")  # Adds comma place of negative index
                index_offset += 1  # Every time a comma is added, the index of all items in list are increased by 1 from the back
        str_num = "".join(lis_num)  # Joins list back together into string
    else:  # If the number is less than or equal to 3 digits long, don't separate with commas
        str_num = str(num)
    return str_num
© www.soinside.com 2019 - 2024. All rights reserved.