How to fix IndexError: string index out of range

Strings are an essential part of just about any programming language. A string is an array of characters . The string index out of range means that the index you are trying to access does not exist. In a string, that means you're trying to get a character from the string at a given point. If that given point does not exist , then you will be trying to get a character that is not inside of the string.


Python string index out of range

example

numbers = "12345678" print(numbers[8])

output

Traceback (most recent call last): File "sample.py", line 2, in <module> print(numbers[8]) IndexError: string index out of range

Let's take the above example:


Python IndexError

try following code:

numbers[0] output: 1
numbers[4] output: 5
numbers[7] output: 8

But what happens if we request index 14?

numbers[8]

output

Traceback (most recent call last): File "sample.py", line 2, in <module> print(numbers[8]) IndexError: string index out of range

Here we get a string index out of range , because we are asking for something that doesn't exist. In Python, a string is a single-dimensional array of characters. Indexes in Python programming start at 0. This means that the maximum index for any string will always be length-1 . Here that makes your numbers[8] fail because the requested index is bigger than the length of the string.


Python string IndexError

The string index out of range problem has to do with a very common beginner problem when accessing elements of a string using its index. There are several ways to account for this. Knowing the length of your string could certainly help you to avoid going over the index.

numbers = "12345678" print(len(numbers))
output: 8

When you run len() function on "numbers" you get the length of our string as 8. Just note that the length doesn't start at 0, it starts at 1. Since Python uses zero-based indexing , the maximum index of a string is the length of the string minus one. So, you can access the maximum index value of a string is its length minus one .

Handling errors and exceptions is another topic in itself, but here briefly show how to prevent it with string indices.

numbers = "12345678" try: num = numbers[8] print(num) except: print("Exception:Index out of range")

output

Exception:Index out of range

In the above example, the error handled it carefully .