使用 .format() 方法超出范围的元组索引
Tuple Index out of range using .format() method
我正在为随机报价程序编写一些非常简单的代码 - 已阅读有关此问题的各种主题,但无法发现我的错误。该错误在倒数第二行触发。提前致谢。
enter code here
enter 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]}"
我正在为随机报价程序编写一些非常简单的代码 - 已阅读有关此问题的各种主题,但无法发现我的错误。该错误在倒数第二行触发。提前致谢。
enter code here
enter 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]}"