What this error means
You tried to access a character in a string using an index that's too large. Strings are zero-indexed, so a string with 5 characters has indices 0 through 4—not 5.
Common causes
- You used an index larger than the string length minus 1.
- You used
len(string)as an index (should belen(string) - 1). - The string is shorter than you expected (maybe empty).
Example that causes the error
text = "hello"
char = text[5] # IndexError: only indices 0-4 exist
text = ""
char = text[0] # IndexError: empty string has no indices
How to fix it
Check the string length first, or use safe access:
text = "hello"
if len(text) > 5:
char = text[5]
else:
print("Index 5 doesn't exist")
# Or check if string is not empty:
if text:
first_char = text[0] # OK: string has at least one character
Access last character safely
text = "hello"
if text:
last = text[-1] # Gets 'o' (last character)
# Or:
last = text[len(text) - 1] # Also gets 'o'
Use try-except
text = "hello"
try:
char = text[10]
except IndexError:
print("Index out of range")
char = None