Error guide · IndexError
IndexError: string index out of range
You asked for a character at a position the text does not have.
Example
word = "cat" print(word[3])
What Python says
IndexError: string index out of range
As printed by Python 3.12. Other versions may word it slightly differently.
Why it happens
Positions in text start at 0, so a three-letter word has positions 0, 1 and 2. Position 3 is one past the end. A loop that runs to len(word) using <= instead of < causes the same error.
How to fix it
word = "cat" print(word[2]) print(word[-1])
Output: t ⏎ t
Tips
- The last character is at
len(word) - 1, or simplyword[-1]. - Loop with
for ch in word:when you do not need the position. - An empty string has no positions at all, so even
s[0]fails on it.