小编JJC*_*INC的帖子

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

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

python string.format python-3.x

0
推荐指数
1
解决办法
95
查看次数

标签 统计

python ×1

python-3.x ×1

string.format ×1