gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:22:28 25 4
gpt4 key购买 nike

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

关于python - 在 Python 中,有没有一种方法可以使用 .format 表示法将列表打印成字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47644532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com