【发布时间】:2018-10-29 20:01:57
【问题描述】:
我正在学习 Learn Python the Hard Way 练习 24,同时将他们在书中使用的所有旧样式格式 (%) 转换为我喜欢的新样式 (.format())。 p>
正如您在下面的代码中看到的,如果我分配一个变量“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-string?
【问题讨论】:
-
猜猜:尝试解压结果
format(*secret_formula(start_point))
标签: python python-3.x string.format