[Solved] IndexError: string index out of range in Python

IndexError: string index out of range error occurs when we tried to access the element that is outside the index range of the string. Strings are a very important part of any programming language. They are simply an array of characters. The string index out of range means that we are trying to access the characters from the string that is not in the range. In this short article, we will discuss how we can solve IndexError: string index out of range error using various methods. Moreover, we will also discuss how to access the string using indexing.

IndexError: string index out of range in Python

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

The IndexError: string index out of range error occurs when we tried to access the characters of the string using an index that is outside the range. In other words, let’s assume that we have a string of length 5 and we are using indexing to access the 7th element, then we will get an index out-of-range error.

For instance, see the example below:

# defining the string
string = "Bashir"

# accessing element of the string
string[8]

Output:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
/tmp/ipykernel_262786/3200701714.py in <module>
      3 
      4 # accessing element of the string
----> 5 string[8]

IndexError: string index out of range

As you can see, we got the IndexError: string index out of range error because the length of the string is less than the index.

Now let us move toward the solutions:

Solution-1: Understanding the indexing in Python

If you know how indexing works in Python, you can then easily solve the issue. In Python, the indexing starts from zero which means the 0 corresponds to the first element, one to the second element, and so on:

ndexError: string index out of range in Python

As you can see, the indexing starts from 0 and goes on.

You can use the len() function in Python to get the length of the string and then accordingly you can use indexing. For example, if we want to access the last element of the string, we can use the len() method to find the length and then access the last element as shown below:

# defining the string
string = "ABCDEF"

# using len
print(len(string))

Output:

6

As you can see that the output is 6 in this case which means the total length of the string is 6. This means we can access the last element by subtracting on from the total length because the indexing starts from 0.

# defining the string
string = "ABCDEF"

# accessing last element
print(string[len(string)-1])

Output:

F

If you will forgot to subtract 1 from the total length of the string and try to access the last element using it, you will get IndexError: string index out of range error as shown below:

# defining the string
string = "ABCDEF"

# accessing last element
print(string[len(string)])

Output:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
/tmp/ipykernel_262786/309173443.py in <module>
      3 
      4 # accessing last element
----> 5 print(string[len(string)])

IndexError: string index out of range

As you can see, we get the same error because again the indexing is out of range.

Solution-2: Using negative indexing

Python also allowed negative indexing as well which is pretty straightforward when you want to access the last element. The negative indexing starts from -1 which corresponds to the last element, -2 corresponds to the second last element, and so on.

IndexError: string index out of range-error

To access the last element, we can use negative -1. Let us take an example and see how it works:

# defining the string
string = "ABCDEF"

# accessing last element
print(string[-1])

Output:

F

As you can see, we got the last element using negative indexing.

Solution-3: Using try-except block

In Python, we have a try-except block which helps us to handle errors. First, the try block will be executed and if an error occurs, then instead of giving an error, the except block will execute.

Let us see how we can use the try-except block to handle the IndexError: string index out of range error in Python.

# defining the string
string = "ABCDEF"

# try block
try:
    # accessing last element
    print(string[10])

# except block
except:
    print("There is an error in the indexing")

Output:

There is an error in the indexing

As you can see, the code runs successfully by giving a message that there is a problem with the indexing.

Solution-4: Using index slicing

Index slicing is used when we want to access a sub-string from the string. Let us say that we want to access the last three elements of the string then we can use the slicing indexing.

In the following example, we will use negative indexing to get the three elements:

# defining the string
string = "ABCDEF"

# slicing
string[-3:]

Output:

DEF

As you can see, we were able to get the last three elements:

Here is another method without using negative indexing:

# defining the string
string = "ABCDEF"

# slicing
string[3:]

Output:

DEF

As you can see, we were able to access the last three elements using slicing.

Another FUN fact about slicing is that if you used an index value out of range for slicing, you will not get IndexError: string index out of range error. For example, lets us take the following example, where we want to access the elements from 3 to 87.

# defining the string
string = "ABCDEF"

# slicing
string[3:87]

Output:

DEF

NOTE that we got the last three elements without getting any errors.

Solution-5: Using if-else statements:

Another alternative to running the code without getting any errors is using the if-else statements. We can check if the index of the string is out of range or not. For example, in the following code, the if statement checks if the index is less than the length of the array or not. If it is less than the length of the array, then the if statement is executed, if not then the else statement will be executed.

# defining the string
string = "ABCDEF"

# index value
ind = 9

# if statement
if ind < len(string):
    string[ind]
    
# else statement
else:
    print("The index value is greater then length of string")

Output:

The index value is greater then length of string

As you can see, we didn’t get the error this time.

Understanding the error IndexError: string index out of range

The errors in Python have two main parts. The first part of the error gives information about the category of the error which in this case is the IndexError and the second part gives more specific information about the error which says the string index is out of range.

What is IndexError in Python?

IndexError in Python occurs when we tried to access the index of a list or string but the range of the index is out of the length of the list or string. We can use the len() method in Python to find the length of the string.

Reasons for getting IndexError: string index out of range in Python error

Here are some of the possible reasons for getting IndexError: string index out of range in Python error.

  • Trying to access an index in a string that is out of the range of the string’s length.
  • Using a negative index to access a string in Python, which is not allowed.
  • Using a non-integer value as an index to access a string.
  • Trying to access an index in an empty string, is not allowed.
  • Attempting to access an element in a list or tuple with an index that is out of range.
  • Trying to access a key in a dictionary that does not exist.
  • Using slicing with invalid start, end, or step values.
  • Using an index that is greater than or equal to the length of the string or sequence.
  • Attempting to access a multidimensional array with an index that is out of range.
  • Trying to concatenate two strings where one or both of them are empty strings.

What is a list in Python?

A list in Python is used to store multiple elements in a single variable.

Summary

In this short article, we discussed how we can solve IndexError: string index out of range error. We discussed five different methods to solve IndexError: string index out of range error.

Related issues:

2 thoughts on “[Solved] IndexError: string index out of range in Python”

  1. Pingback: AttributeError: FacetGrid object has no attribute get_figure - Techfor-Today

  2. Pingback: ImportError: Missing optional dependency openpyxl - Techfor-Today

Leave a Comment

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

Scroll to Top