如何在 python 中将浮点数格式化为字符串?

How can I format a float as a string in python?

def main():
    M = float(input('Please enter sales for Monday: '))
    T = float(input('Please enter sales for Tuesday: '))
    W = float(input('Please enter sales for Wednesday: '))
    R = float(input('Please enter sales for Thursday: '))
    F = float(input('Please enter sales for Friday: '))
    sales = [M, T, W, R, F]

        total = 0 

    for value in sales:
        total += value

    print ('The total sales for the week are: $',total('.2f'))

main()

使用 .2f 格式时出现此异常:

TypeError: 'float' object is not callable

如果我删除 .2f 脚本运行正常,但格式不是我想要的,它显示为:

The total sales for the week are: $ 2500.0

我希望它有 2 个小数位并且 $ 符号之间没有 space。

python 还很陌生,正在学习基础知识。非常感谢您的帮助。

您可以使用内置的 sum 函数汇总列表。试试 print(sum(sales)).

你可以像这样格式化你的浮点数print(f'Week is {sum(sales):.2f}')

小尼特。

继续黑客攻击!做笔记。

这是一个使用 python 的 3 f-string 功能的解决方案

print (f'The total sales for the week are: {total:.2f}')

在 python 中,您可以用多种方式格式化字符串。这里有一些关于它们的好资源:

对于您的情况,您可以像这样格式化总值:

>>> total = 1234.56789

>>> "{:.2f}".format(total)
'1234.57'

>>> "%.2f" % total
'1234.57'

# This only works in 3.7 and later
>>> f"{total:.2f}"
'1234.57'

对于您的特定情况,您可以一次性格式化整个 print 字符串:

print(f"The total sales for the week are: ${total:.2f}")

替换

print ('The total sales for the week are: $',total('.2f'))

为了

print ('The total sales for the week are: $',"{0:.2f}".format(total))

在此处查看Limiting floats to two decimal points

示例代码

def main():
    M = float(input('Please enter sales for Monday: '))
    T = float(input('Please enter sales for Tuesday: '))
    W = float(input('Please enter sales for Wednesday: '))
    R = float(input('Please enter sales for Thursday: '))
    F = float(input('Please enter sales for Friday: '))
    sales = [M, T, W, R, F]

    total = 0 

    for value in sales:
        total += value
    total = "{0:.2f}".format(total)
    print ('The total sales for the week are: $' + str(total))

main()

只需更正一下:

print('The total sales for the week are:',format(total,('.2f')),'$')

Python 中的格式化程序允许您使用花括号作为值的占位符,这些值将通过 str.format() 方法传递。

根据您的要求

total = 0 
print ('The total sales for the week are: $',"{0:.2f}".format(total))