python - 如何在 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 个小数位,并且 $ 符号之间没有空格。
对 python 和学习基础知识仍然很陌生。非常感谢您的帮助。
解决方案
这是使用 python 的 3 f-string 功能的解决方案
print (f'The total sales for the week are: {total:.2f}')
推荐阅读
- microsoft-teams - 同一租户中的所有用户是否共享 MS Teams Bot 的 serviceUrl?
- functional-programming - 支持操作员作为一等公民的语言如何遵守操作顺序?
- wordpress - Wordpress - 如何在循环内获取小尺寸缩略图
- laravel - 在 MariaDB 上使用 JSON 字段时出现迁移错误
- python - _tkinter.TclError: bad window path name ".!toplevel" 使关闭按钮退出窗口而不出错
- python - Bash脚本到Python不知道如何
- java - 单击android上的手机硬件后退按钮时从未调用过onResume?
- python - 使用 PyQt5 提取网页的某些部分并显示它们
- javascript - Firebase 数据库数据检索遇到问题
- reactjs - React:componentDidUpdate - 当我更新数组中的对象时,以前的状态与当前状态相同