如何在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
格式时,我收到此异常:
With the .2f
format I am getting this exception:
TypeError: 'float' object is not callable
如果我删除 .2f
脚本运行正常,但格式不是我想要的,它显示为:
If I remove the .2f
the script runs properly but the formatting is not how I would like it, it displays as:
The total sales for the week are: $ 2500.0
我希望它有 2 个小数位并且 $ 符号之间没有空格.
I would prefer to have it so that there are 2 decimal places and no space between the $ sign.
对 Python 还是个新手,正在学习基础知识.非常感谢您的帮助.
Still new to python and learning the basics. Your help is greatly appreciated.
答
replace
print ('The total sales for the week are: $',total('.2f'))
为了
print ('The total sales for the week are: $',"{0:.2f}".format(total))