IndexError: string index out of range

Loading

The error message:

IndexError: string index out of range

occurs when you try to access an index in a string that does not exist. Since strings are immutable sequences of characters, their indices must be within the valid range.


1. Causes and Solutions

Cause 1: Accessing an Index That Does Not Exist

If you try to access an index greater than or equal to the string’s length, Python raises an IndexError.

Incorrect Code:

text = "hello"
print(text[5]) # Error: Index 5 is out of range (valid indices: 0, 1, 2, 3, 4)

Solution: Ensure the index is within the string’s length.

if len(text) > 5:
print(text[5])
else:
print("Index is out of range")

Cause 2: Using a Loop with an Incorrect Range

If you loop beyond the valid indices, you may get this error.

Incorrect Code:

text = "Python"
for i in range(7): # Error: range(7) includes index 6, which does not exist
print(text[i])

Solution: Use len(text) to avoid out-of-range errors.

for i in range(len(text)):  # Safe iteration
print(text[i])

Or use a direct iteration approach.

for char in text:
print(char)

Cause 3: Negative Index Beyond String Range

Negative indices refer to elements from the end, but if they exceed the string size, an error occurs.

Incorrect Code:

text = "hello"
print(text[-6]) # Error: Only -1, -2, -3, -4, and -5 are valid

Solution: Ensure the negative index is within range.

if -6 >= -len(text):
print(text[-6])
else:
print("Negative index out of range")

Cause 4: Indexing from an Empty String

If a function returns an empty string and you try to access an index, this error occurs.

Incorrect Code:

empty_string = ""
print(empty_string[0]) # Error: No characters in the string

Solution: Check if the string is empty before accessing an index.

if empty_string:
print(empty_string[0])
else:
print("String is empty")

Cause 5: Slicing with an Out-of-Range Index

If you try to slice a string using an invalid start or stop index, it does not raise an error but returns an empty string.

Example:

text = "hello"
print(text[10:15]) # No error, but returns ''

Solution: Use min() to avoid invalid slicing.

start, end = 2, 10
print(text[start:min(end, len(text))]) # Outputs 'llo'

Leave a Reply

Your email address will not be published. Required fields are marked *