Python .format上的键错误
我得到一些语法错误,我需要帮助理解 这是我写的代码-Python .format上的键错误,python,floating-point,string-formatting,Python,Floating Point,String Formatting,我得到一些语法错误,我需要帮助理解 这是我写的代码- offer=float(input("What's your offer")) demand=float(500) agree=offer+demand/2 print("You offer {f:0} " .format(offer) + "but the merchant wants {f:1} " .format(demand)) print("You finally agree on" + agree) 这是我收到的错误- Fil
offer=float(input("What's your offer"))
demand=float(500)
agree=offer+demand/2
print("You offer {f:0} " .format(offer) + "but the merchant wants {f:1} " .format(demand))
print("You finally agree on" + agree)
这是我收到的错误-
File "c:\users\mariy\documents\visual studio 2013\Projects\PythonApplication4\PythonApplication4\module1.py", line 5, in <module>
print("You offer {f:0} " .format(offer) + "but the merchant wants {f:1} " .format(demand))
KeyError: 'f'
文件“c:\users\mary\documents\visualstudio 2013\Projects\PythonApplication4\PythonApplication4\module1.py”,第5行,在
打印(“您提供{f:0}.format(offer)+”但商户需要{f:1}.format(demand))
键错误:“f”
您正在尝试使用.format()
,但是{}
中引用浮点值的参数前面应该是:
,而不是前面
0
和1
在代码执行过程中也会引起一些问题,不需要它们。但是,如果您只想使用一种格式操作,则数字将是.format()
例如:“这是数字{1},这是{0}”。格式(“零”,“一”)
将产生以下输出这是数字,这是零
最后一次打印也会造成问题,因为无法将字符串和整数连接起来
经过一些更正后,您的代码应该如下所示:
print(“您提供{:f},但商户需要{:f}”。格式(提供,需求))
打印(“您最终同意{:f}”。格式(同意))
如果要限制十进制大小写的数量,可以在{}
参数中定义它们
例如:{.2f}
将打印带有两个十进制大小写的浮点数KeyError
出现,因为格式规范{f:0}
告诉.format()
查找键为f
的dict,而该dict不存在
您可能希望使用以下选项:
print "You offer ${offer:6.2f} but the merchant wants ${demand:6.2f}".format(offer=200.0,demand=300.0)
你出价200美元,但商人要300美元
您可以将200.0
和300.0
替换为要使用的变量名,将$
替换为其他货币符号,或不替换任何符号
注意语法:
$
不是格式语法的一部分。它是逐字印刷的
使用{keyname:spec}
keyname
部分来自传递给.format()
的kwargs
,即如果我们有{demand}
那么我们必须有.format(demand=something)
或.format(somedict)
其中somedict
有demand
spec
是放置位数、一个点、小数点后的数字以及变量类型的地方,如f
中的浮点。因此6.2f
表示总共6位数字,小数点后2位,浮点