Home > front end >  Tuple Index out of range using .format() method
Tuple Index out of range using .format() method

Time:03-27

I am writing some very simple code for a random quote program - have read various threads on this issue but cannot spot my error. The error is triggered on the penultimate line. Thanks in advance.

enter code here enter code hereimport random

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)

CodePudding user response:

You missed providing value for {1} for quote. Update quote to this and it works.

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

Output

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

CodePudding user response:

To add to above answer, you can also use f-strings if you are using Python 3.6 and above. You can use it as follows:

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