BugHunt

IndexError: string index out of range

Same cause as the list version: you asked for a character position the string does not have.

PythonOff-by-one errors

What it means

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.

Common causes

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 += 1

Works

i = 0
while i < len(text):
    print(text[i])
    i += 1

How 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.

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.

Other common errors