IndexError: string index out of range in Python

avatar

Borislav Hadzhiev

Last updated: Apr 22, 2022

banner

Photo from Unsplash

IndexError: string index out of range in Python #

The Python "IndexError: string index out of range" occurs when we try to access an index that doesn't exist in a string. Indexes are zero-based in Python, so the index of the first character in the string is 0, and the index of the last is -1 or len(my_str) - 1.

indexerror string index out of range

Here is an example of how the error occurs.

main.py
my_str = 'hello' # ⛔️ IndexError: string index out of range result = my_str[100]

The string hello has a length of 5. Since indexes in Python are zero-based, the first index in the string is 0, and the last is 4.

hello
01234
If we try to access any positive index outside the range of 0-4, we would get an IndexError.

If you need to get the last character in a string, use -1.

main.py
my_str = 'hello' result = my_str[-1] print(result) # 👉️ o print(my_str[-2]) # 👉️ l

When the index starts with a minus, we start counting backwards from the end of the string.

If you need to get the length of the string, use the len() function.

main.py
my_str = 'hello' print(len(my_str)) # 👉️ 5 idx = 5 # ✅ checking if index exists before accessing it if len(my_str) > idx: print(my_str[idx]) else: # 👇️ this runs print(f'index {idx} is out of range')

The len() function returns the length (the number of items) of an object.

The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).

If a string has a length of 5, then its last index is 4 (because indexes are zero-based).

This means that you can check if the string's length is greater than the index you are trying to access.

An alternative approach is to use a try/except block and handle the error.

main.py
my_str = 'hello' try: result = my_str[100] print(result) except IndexError: print('index out of range') # handle error here

We tried accessing the character at index 100 of the string which raised an IndexError exception.

You can handle the error or use the pass keyword in the except block.

Note that if you try to access an empty string at a specific index, you'd always get an IndexError.

main.py
my_str = '' print(my_str) # 👉️ "" print(len(my_str)) # 👉️ 0 # ⛔️ IndexError: string index out of range print(my_str[0])

You should print the string you are trying to access and its length to make sure the variable stores what you expect.

Note that if you use string slicing, you don't get an error if the starting index is out of range.

main.py
my_str = 'hello' print(my_str[100:]) # 👉️ "" print(my_str[2:]) # 👉️ "llo"

The first example returns an empty string and doesn't cause an error.

The syntax for string slicing is my_str[start:stop:step].

If you don't specify a value for the stop index, you'd get a substring that contains the characters until the end of the original string.

If you only need a single character, specify a stop index.

main.py
my_str = 'hello' print(my_str[100:101]) # 👉️ "" print(my_str[2:3]) # 👉️ "l"

Notice that the start index is inclusive, whereas the stop index is exclusive.

In the second example, we start at index 2, get the character at index 2 and stop.

This approach is useful if you would rather get an empty string than have to handle an IndexError if the index you are trying to access is out of range.

Conclusion #

The Python "IndexError: string index out of range" occurs when we try to access an index that doesn't exist in a string. Indexes are zero-based in Python, so the index of the first character in the string is 0, and the index of the last is -1 or len(my_str) - 1.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.