IndexError: String Index Out of Range

IndexError: string index out of range

Quick Answer

You are accessing a character position that does not exist. Use slicing which gracefully handles out-of-range boundaries, or check string length first.

Why This Happens

Strings in Python are sequences and indexing follows the same rules as lists. A string of length 5 has valid indices 0-4. Unlike indexing, slicing (s[0:100]) gracefully handles boundaries.

The Problem

text = 'hello'
char = text[5]

The Fix

text = 'hello'
chars = text[0:10]  # Returns 'hello', no error
# Or check: if len(text) > 5: char = text[5]

Step-by-Step Fix

  1. 1

    Check string length

    Verify with len(s) before indexing.

  2. 2

    Use slicing instead

    s[start:end] handles out-of-range gracefully.

  3. 3

    Handle edge cases

    Account for empty strings and shorter-than-expected strings.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free