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

2024-06-07 22:57:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在进行学习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字符串?你知道吗

Tags: and函数formatsecrethave样式startpoint
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)))

但是,用*解包返回值,将元素作为单独的参数传递,将更简单、更常规:

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

这是因为要传递一个由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)

相关问题 更多 >

    热门问题