格式化字符串时,不能在format方法内使用函数调用

2024-06-07 11:07:17 发布

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

我有一些密码:

def secret_formula(started):
    jelly_beans = started * 500
    jars = jelly_beans / 1000
    crates = jars / 100
    return jelly_beans, jars, crates

start_point = 10000

#print ('We\'d have {0} beans, {1} jars, and {2} crates.'
        .format(secret_formula(start_point)))

print ('We\'d have %d beans, %d jars, and %d crates.'
        % secret_formula(start_point))

我的问题是关于最后两个陈述。注释掉的一个不起作用(返回索引超出范围错误),但另一个起作用。为什么?我怎样才能使注释掉的语句起作用呢?你知道吗

提前感谢:)

拉尔斯


Tags: and密码secretdefhavestartpointwe
1条回答
网友
1楼 · 发布于 2024-06-07 11:07:17

注释掉的行应该是

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

注意*前面的secret_formula(...),它告诉Python在将值传递给format()时解压结果。你知道吗

相关问题 更多 >

    热门问题