IndexError: string index out of range
What it means
You asked for a character position the string does not have. Positions start at 0, so 'cat' has positions 0, 1 and 2, and an empty string '' has none. Slices such as text[0:10] never raise this error, only single positions like text[10] do.
1. Using `len()` as the last position
This raises the error
Traceback (most recent call last): File "<exec>", line 2, in <module> IndexError: string index out of range
The fix
n n
len(word) is 6, but the positions run from 0 to 5. Use len(word) - 1, or -1, which always means the last character.
2. An empty string
This raises the error
Traceback (most recent call last): File "<exec>", line 2, in <module> IndexError: string index out of range
The fix
? ''
An empty string has no first character. Check it first, or use a slice like name[:1], which returns an empty string instead of failing.
3. Comparing each character with the next one
This raises the error
double l double o Traceback (most recent call last): File "<exec>", line 3, in <module> IndexError: string index out of range
The fix
double l double o
When the loop reads text[i + 1], the last character has no next one. Stopping at len(text) - 1 keeps both positions inside the string.
When you see this error, check
- Print
repr(text)andlen(text)just before the failing line:repr()shows an empty string as''. - Use
text[-1]for the last character. - Check
if text:before readingtext[0]. - Use a slice like
text[:1]when an empty result is fine.
Related errors
All Python errors · How to read a traceback · Step through your code