IndexError: string index out of range
IndexError: string index out of range in Python means same cause as the list version: you asked for a character position the string does not have.
How do I fix IndexError: string index out of range?
To fix IndexError: string index out of range in Python, locate the line causing the error and check the values right before it runs. Most occurrences happen because of reaching for the last character with len. Apply a defensive check or safe fallback, make sure collections or objects exist before access, and verify return values from upstream functions.
What does IndexError: string index out of range mean?
Strings index from 0, so "hello" has valid indices 0 to 4. text[len(text)] is always one past the end, and any index on an empty string fails immediately.
Why does IndexError: string index out of range happen?
1. Reaching for the last character with len
The final character sits at len - 1, or more simply at -1.
Breaks
last = text[len(text)]Works
last = text[-1]2. The string is empty
text[0] raises on "". Common with input that was stripped to nothing, or a missing field.
Breaks
initial = name[0]Works
initial = name[0] if name else ""3. Walking a string with an index that outpaces it
A while loop whose condition uses <= rather than < steps one too far.
Breaks
i = 0
while i <= len(text):
print(text[i])
i += 1Works
i = 0
while i < len(text):
print(text[i])
i += 1How to find it in your own code
Prefer slicing over indexing where you can — text[-1:] returns "" on an empty string instead of raising. When you must index, check the string is non-empty first.
Try it: fix this bug
easylast_char("hello") crashes: IndexError: string index out of range.
def last_char(text):
return text[len(text)]Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.