String IndexError(index out of range) Exception
An IndexError
is raised when you try to access a character at a position that doesn’t exist in a string.
This happens when the index is greater than the highest available position in the string.
For example, the string "hello"
has 5 characters (index 0 to 4), so accessing s[5]
or beyond will raise an IndexError.
String indices start from 0, so in the string "hello", s[4]
is valid, but s[5]
is not.
To prevent this error, ensure that you check the length of the string and only access indices that fall within the valid range.
IndexError Example
Example of IndexError
word = "Python"
# Correct indexing
print(word[0]) # 'P'
# IndexError occurrence
print(word[6]) # IndexError: string index out of range
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.