我正在学习 Python the Hard Way 练习 24,同时将他们在书中使用的所有旧样式格式 (%) 转换为我喜欢的新样式 (.format())。
正如你在下面的代码中看到的,如果我分配一个变量“p”,我可以成功地解包函数返回的元组值。但是当我直接使用该返回值时,它会抛出一个 TypeError。
def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates
start_point = 10000
#Old style
print("We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point))
#New style that works
print("We'd have {p[0]:.0f} beans, {p[1]:.0f} jars, and {p[2]:.0f} crates.".format(p=secret_formula(start_point)))
#This doesn't work:
print("We'd have {0:.0f} beans, {1:.0f} jars, and {2:.0f} crates.".format(secret_formula(start_point)))
抛出错误:
Traceback (most recent call last):
File "ex.py", line 16, in <module>
print("We'd have {0:.0f} beans, {1:.0f} jars, and {2:.0f} crates.".format(secret_formula(start_point)))
TypeError: unsupported format string passed to tuple.__format__
有人可以解释为什么在 .format() 中直接使用函数不起作用吗?
如何将其转换为 f 字符串?
神不在的星期二
相关分类