【问题标题】:In Python, is there a method to print lists into a string using .format notation?在 Python 中,是否有使用 .format 表示法将列表打印成字符串的方法?
【发布时间】:2017-12-05 01:11:27
【问题描述】:

一个简单的 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

【问题讨论】:

    标签: python string list tuples string.format


    【解决方案1】:

    您可以使用*解包列表:

    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 ListsFormat examples

    【讨论】:

      猜你喜欢
      • 2019-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-01
      • 2022-01-11
      • 1970-01-01
      相关资源
      最近更新 更多