How to Fix: IndexError: string index out of range

3D illustration of a pointer trying to access a character index that doesn't exist in a word, representing a String Index Out of Range error.

If your Python script just crashed with an IndexError: string index out of range, you are dealing with a classic off-by-one error or a dirty data issue.

This error means your code is trying to read a specific character position (an index) that simply does not exist in the string you provided.

Just like with lists, Python strings are fundamentally just sequences of characters.

text = "Python"
# P = index 0
# y = index 1
# ...
# n = index 5

The length is 6, but the last index is 5.

The Cause

Trying to access a character that doesn’t exist.

text = "Hi"
print(text[2]) 
# CRASH! Index 2 doesn't exist (only 0 'H' and 1 'i' exist)

Common Scenario: Empty Strings

This often happens when looping through data where some entries might be blank.

def get_first_letter(word):
    return word[0]  # DANGER!

print(get_first_letter("")) 
# CRASH! An empty string has NO index 0.

The Fix

Always check if the string is empty before trying to access a specific index.

def get_first_letter(word):
    if len(word) > 0:  # Or just 'if word:'
        return word[0]
    else:
        return None

Similar Posts

Leave a Reply