Online Tutorials & Training Materials | STechies.com
Register Login

IndexError: string index out of range

28 Jan 2020 1:38 pm || 0

IndexError string index out of range

We all know that all the elements in an array or string in Python are defined by their indices. To access a specific element, you have to mention its index value. But in some cases you may encounter an error called “IndexError string index out of range”. This error is raised when the string index you are trying to access or operate is out of the range you are mentioning in your code.

The way to fix this error is to mention the correct index of the desired element of operation. You can also see if there are indentation mistakes in your code that can also be then reason.

Example 1

Let us take a look at an example,

# Declare string
str1 = 'Stechies'

# Print string value at index 10
print(str1[10])

Output:

File "pyprogram.py", line 3, in <module> 
print(str1[10])
IndexError: string index out of range

In the above example, we are trying to print the value at index 10 but in string “STECHIES” it has only 7 indices.

String Index

Solution:

# Declare string
str1 = 'Stechies'

# Print string value at index 7
print(str1[7])
print(str1[6])
print(str1[5])
print(str1[4])
print(str1[2])

Output:

s
e
i
h
e

In the solution code above, the str1 variable is assigned a string Stechies. The string has 8 indices, meaning the index starts from 0 and ends at 7. The print() method is used for printing the indices at positions 7,6,5,4 and 2.

The code executes without errors. The error IndexError string index out of range is avoided. This is because all of the string indices mentioned within the print statement are within the range of the string Stechies.

IndexError string index out of range

Example 2 with While Loop

Take a look at another piece of code:

# Declaring String
str1 = 'STECHIES'
i=0
# while loop less then and equal to list "str1" length.
while i <= len(str1):
    print(str1[i])
    i += 1

Output:

  File "pyprogram.py", line 7, in <module>
    print(list_fruits[i])
IndexError: string index out of range

Solution:

# Declaring String
str1 = 'STECHIES'
i=0
# while loop less then to list "str1" length.
while i < len(str1):
    print(str1[i])
i += 1

Output:

S
T
E
C
H
I
E
S

Explanation

In the solution code, the string “STECHIES” within the variable str1 has a length of 8. The variable i is initialized with the value 0. Then there is a while loop that checks whether the value of i is less than the length of the string. As long as the condition is True, the loop continues printing the elements at the ith index. The value of i is incremented during each iteration.

So when the value i is greater than the length of the string, the looping condition is False. The while loop stops executing. The code does not try to access indices that are out of range. Hence, the IndexError: string index out of range is avoided successfully.