'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)
Solution 1:[1]
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
Solution 2:[2]
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]}"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Manjunath K Mayya |
| Solution 2 | Vaibhav Jadhav |
