user2127168
user2127168

Reputation: 91

Tuple Index out of range using .format() method

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)

Upvotes: 0

Views: 86

Answers (2)

Vaibhav Jadhav
Vaibhav Jadhav

Reputation: 2076

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]}"

Upvotes: 1

Manjunath K Mayya
Manjunath K Mayya

Reputation: 1118

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

Upvotes: 1

Related Questions