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

时间:2018-10-29 20:01:58

标签: python python-3.x string.format

我正在经历困难方法学习Python 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__
  1. 有人可以解释为什么直接在.format()中使用函数吗 不行?
  2. 如何将其转换为f字符串?

2 个答案:

答案 0 :(得分:6)

那是因为您要传递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)

答案 1 :(得分:2)

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

要在将其作为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)))

但是,用*代替 unpack 返回值将元素作为单独的参数传递会更简单,更常规:

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