Index error: string index out of range (Resolved)

Published December 30, 2020


Introduction

Strings are still an integral portion of any programming language. A string can be an array of characters. Even the string index out of range usually means the index you're looking for doesn't exist. At some string, which usually means you are attempting to receive yourself a character out of the string at a particular level. If that specified position doesn't exist, subsequently, you definitely might be hoping to find yourself a personality that isn't interior to the string.

 

Read how to remove Last character from String in Python

 

For example:

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

 

Output

 

String index out of range python

 

Now try the following code-

numbers = "12404608"
print(numbers[7])

 

Output: 8

string index out of range python

 

What happens if we index 20? Let's check

numbers = "12404608"
print(numbers[20])

 

String index out of range python

 

We received an error string index out of range, as we're seeking something which will not exist. Back in Python, a string can be actually just a single-dimensional array of characters. Indexes in Python programming begin from 0. It means that the index for any string will up to length-1. This creates your amounts [8] fall short as the requested index is larger compared to the length of this string.

 

Summary

In python string indexing starts from 0 that means the index for any string will be upto length -1. 

Even the string index out of range error must complete having a common beginner issue when obtaining parts of the string with its index. You'll find a number of techniques to account for because of it in particular. Recognizing that the length of one's string can undoubtedly give you the capacity to keep going through your index

 

numbers = "12404608"
print(len(numbers))

 

Output:

string index out of range python

 

You will notice that when you are running len() function, you are getting the length of the string as 8 and the length is not starting from 0. As python programming uses 0-level indexing, the maximum index of any string is equal to the length of the string - 1. So you can easily get the max index of any string by subtracting 1 by the length of the string.

 

Hence the index error: string index out of range is resolved

 

 


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

655 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions