使用.format()方法的元组索引超出范围



我正在为一个随机报价程序编写一些非常简单的代码-已经阅读了关于这个问题的各种线程,但无法发现我的错误。该错误在倒数第二行触发。提前谢谢。

enter code hereenter code here导入随机

quote_str = [
["Tis better to have loved and lost than never to have loved at all",
"Alfred Lord Tennyson"],
["To be or not to be, that is the question.","William Shakespeare"],
["No one can make you feel inferior without your consent.","Eleanor Roosevelt"],
["You are your best thing.","Toni Morrison"]]
x = random.choice([0,1,2,3])
quote = "Quote: {0} Author: {1}".format(quote_str[x][0])
print(quote)

您错过了为{1}quote提供值。将quote更新到这个位置,它就工作了。

quote = "Quote: {0} Author: {1}".format(quote_str[x][0], quote_str[x][1])

输出

Quote: You are your best thing. Author: Toni Morrison

要添加到上面的答案中,如果您使用Python 3.6 and above,也可以使用f-strings。您可以按如下方式使用它:

quote = f"Quote: {quote_str[x][0]} Author: {quote_str[x][1]}"

最新更新