【问题标题】:Can't use a function call inside the format method, when formatting a string格式化字符串时,不能在格式化方法中使用函数调用
【发布时间】:2011-11-30 12:47:32
【问题描述】:

我有一些代码:

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))

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

提前致谢:)

拉尔斯

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    注释掉的行应该是

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

    注意* 之前的*——它告诉Python 在将值传递给format() 时解包结果。

    【讨论】:

      猜你喜欢
      • 2013-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-26
      相关资源
      最近更新 更多