Lecture
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
Quiz
0 / 1
An IndexError occurs if you try to access an index beyond the length of the string.
True
False
Lecture
AI Tutor
Help
Code Editor
Run
Generate
Execution Result