Skip to content
Home » Python error: “IndexError: string index out of range”

Python error: “IndexError: string index out of range”

To solve Python error: “IndexError: string index out of range” error follow below methods.

ERROR LOG

“IndexError: string index out of range”

How to solve Python error: “IndexError: string index out of range” ?

Strings are a fundamental component of almost any programming language. A string is a collection of characters. The string index out of range error indicates that the index you’re attempting to access does not exist. In a string, this signifies you’re attempting to extract a character from the string at a specific position. If that specified point does not exist, you will be attempting to obtain a character that is not contained within the string.

Example:

s = 'gfhs'
print(s[8])

Output:

IndexError                                Traceback (most recent call last)
<ipython-input-1-1a2154a84897> in <module>()
      1 s = 'gfhs'
----> 2 print(s[8])

IndexError: string index out of range

We got above error because we are requesting something that does not exist, we obtain a string index that is out of range. A string in Python is a one-dimensional array of characters. In Python programming, indexes begin at 0. As a result, the maximum index for any string is always length-1. Because the required index is more than the length of the string, your s[8] fail.

Hope the above solution works.

Also read : TypeError: ‘encoding’ is an invalid keyword argument for this function