在 .format() 中使用函数时出现类型错误

TypeError when Using Function in .format()

我正在完成 学习 Python 困难之路练习 24,同时将他们在书中使用的所有旧样式格式 (%) 转换为我喜欢的新样式(.format()).

正如您在下面的代码中看到的,如果我分配一个变量 "p",我可以成功地解压缩由函数编辑的元组值 return。但是当我直接使用那个 return 值时,它会抛出一个 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__
  1. 有人可以解释为什么直接在 .format() 中使用函数吗? 不行?
  2. 如何将其转换为 f 字符串?

那是因为您传递了一个包含 3 个值的元组作为函数的输出

要完成这项工作,您需要使用 *

解压元组
print("We'd have {0:.0f} beans, {1:.0f} jars, and {2:.0f} crates.".format(*secret_formula(start_point)))

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

def func(param, variable):
  return None

args = {'param': 1, 'variable': 'string'}
func(*args)

按位置将 secret_formula 的 return 值传递给 format 并不比通过关键字传递更直接。无论哪种方式,您都将 return 值作为单个参数传递。

要在将参数作为 p 关键字参数传递时访问该参数的元素,请使用 p[0]p[1]p[2]。同样,按位置传递参数时,您必须访问 0[0]0[1]0[2] 的元素,并指定位置 0。 (这是 str.format 处理格式占位符的具体方式,而不是正常的 Python 索引语法):

print("We'd have {0[0]:.0f} beans, {0[1]:.0f} jars, and {0[2]:.0f} crates.".format(
      secret_formula(start_point)))

但是,将 解压 return 值与 * 相比,将元素作为单独的参数传递会更简单、更常规:

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