在.format()中使用函数时的TypeError

JJC*_*INC 0 python string.format python-3.x

我正在通过Learn 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)))
Run Code Online (Sandbox Code Playgroud)

引发错误:

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__
Run Code Online (Sandbox Code Playgroud)
  1. 有人可以解释为什么直接使用.format()中的函数不起作用?
  2. 如何将其转换为f-string?

MrE*_*MrE 6

那是因为你传递了一个由3个值组成的元组作为函数的输出

要使这项工作,您需要解压缩元组 *

print("We'd have {0:.0f} beans, {1:.0f} jars, and {2:.0f} crates.".format(*secret_formula(start_point)))
Run Code Online (Sandbox Code Playgroud)

您也可以使用对象来执行此操作,其中键应与函数参数名称匹配,例如:

def func(param, variable):
  return None

args = {'param': 1, 'variable': 'string'}
func(*args)
Run Code Online (Sandbox Code Playgroud)