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.
○
✕
학습 자료
AI 튜터
디자인
업로드
수업 노트
즐겨찾기
도움말
코드 에디터
코드 실행
코드 생성
실행 결과