【问题标题】:TypeError when Using Function in .format()在 .format() 中使用函数时出现类型错误
【发布时间】: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__
  1. 有人能解释一下为什么在.format() 中直接使用函数吗 不行?
  2. 如何将其转换为 f-string?

【问题讨论】:

  • 猜猜:尝试解压结果format(*secret_formula(start_point))

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


【解决方案1】:

那是因为你传递了一个包含 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)

【讨论】:

  • 我不知道你可以在 python 中做到这一点!
  • 你可以用元组做这个,也可以用对象,其中对象键将是函数的参数名称
【解决方案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)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 2021-09-06
    • 2011-10-17
    • 2017-06-15
    相关资源
    最近更新 更多