Blog |

How to Fix IndexError: string index out of range in Python

How to Fix IndexError: string index out of range in Python
Table of Contents

The Python IndexError: string index out of range error occurs when an index is attempted to be accessed in a string that is outside its range.

What Causes IndexError: string index out of range

This error occurs when an attempt is made to access a character in a string at an index that does not exist in the string. The range of a string in Python is [0, len(str) - 1] , where len(str) is the length of the string. When an attempt is made to access an item at an index outside this range, an IndexError: string index out of range error is thrown.

Python IndexError: string index out of range Example

Here’s an example of a Python IndexError: string index out of range thrown when trying to access a character outside the index range of a string:

my_string = "hello"
print(my_string[5])

In the above example, since the string my_string contains 5 characters, its last index is 4. Trying to access a character at index 5 throws an IndexError: string index out of range:

Traceback (most recent call last):
  File "test.py", line 2, in <module>
    print(my_string[5])
          ~~~~~~~~~^^^
IndexError: string index out of range

How to Handle IndexError: string index out of range in Python

The Python IndexError: string index out of range can be fixed by making sure any characters accessed in a string are within the range of the string. This can be done by checking the length of the string before accessing an index. The len() function can be used to get the length of the string, which can be compared with the index before it is accessed.

If the index cannot be known to be valid before it is accessed, a try-except block can be used to catch and handle the error:

my_string = "hello"
try:
    print(my_string[5])
except IndexError:
    print("Index out of range")

In this example, the try block attempts to access the 5th index of the string, and if an IndexError occurs, it is caught by the except block, producing the following output:

Index out of range

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!

Related Resources

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape