使用函数时的字符串格式问题

时间:2012-01-29 23:29:38

标签: python-2.7

我认为这是一个令人尴尬的简单问题,但是三个小时的谷歌搜索和检查stackoverflow没有帮助。

我们说我的代码非常简单:

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 {} beans, {} jars, and {} crates.".format(secret_formula(start_point)))

我发现" IndexError:tuple索引超出范围"会发生什么?所以我只打印secret_formula函数来查看它的样子,它看起来像这样:

(5000000, 5000.0, 50.0)

基本上,它将输出视为一个事物&#39; (我还是很新,对不起,如果我的语言不正确的话)。我的问题是,为什么它会这样对待它,如何让它通过三个输出(jelly_beansjarscrates),以便正确格式化字符串?< / p>

谢谢!

1 个答案:

答案 0 :(得分:1)

字符串的format函数采用可变数量的参数。 secret_formula函数返回一个元组。您想将其转换为参数列表。这是使用以下语法完成的:

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

重要的标准是*字符。它告诉您要将以下iterable转换为要传递给函数的参数列表。

相关问题