在 Python 中,有没有一种方法可以使用 .format 符号将列表打印成字符串?

In Python, is there a method to print lists into a string using .format notation?

一个简单的 Madlibs 练习:

STORY = "This morning I woke up and felt %s because %s was going to finally %s over the big %s %s."

WORD_types = ('an adjective','a pronoun','a verb','an adjective','a noun')

WORD_values = []

for s in WORD_types:
  print "Please give {}.".format(s)
  s = raw_input()
  WORD_values.append(s)

print STORY % tuple(WORD_values)

有没有办法用 .format 符号来完成最后一行?

STORY = "This morning I woke up and felt {} because {} was going to finally {} over the big {} {}."

WORD_types = ('an adjective','a pronoun','a verb','an adjective','a noun')

WORD_values = []

for s in WORD_types:
  print "Please give {}.".format(s)
  s = raw_input()
  WORD_values.append(s)

print STORY.format(WORD_values)

这会引发以下错误:

Traceback (most recent call last):
  File "Madlibs.py", line 12, in <module>
    print STORY.format(WORD_values)
IndexError: tuple index out of range

您可以使用*解压列表:

print STORY.format(*WORD_values)

示例输出:

Please give an adjective
 optimistic
Please give a pronoun
 I
Please give a verb
 drive
Please give an adjective
 scary
Please give a noun
 hill
This morning I woke up and felt optimistic because I was going to finally drive over the big scary hill.

相关文档如下:Unpacking Argument Lists and Format examples.