VOOZH about

URL: https://www.geeksforgeeks.org/python/python-string-index-out-of-range-how-to-fix-indexerror/

⇱ Python string index out of range - How to fix IndexError - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python string index out of range - How to fix IndexError

Last Updated : 23 Jul, 2025

In Python, String index out of range (IndexError) occurs when we try to access index which is out of the range of a string or we can say length of string.

Python strings are zero-indexed, which means first character is at index 0, second at 1, and so on. For a string of length n, valid range will is [0, len(str) -1].

Common Examples of IndexError - string index out of range

How to Handle IndexError: string index out of range in Python

IndexError in String can be handled by ensuring character accessed are within the range of given string, by using len() method.

For positive index, the range must be within [0, len(string) - 1] and for negative index, rage should be [-len(string), -1]. Combined validation [for both +ve and -ve indexing] can be done with -len(string) <= index < len(string).


Use Exception Handling to avoid IndexError

We can handle IndexError exception by using try.. except block. It is used where you cannot ensure index is valid beforehand. For example, where index is generated dynamically or based on user input.


Exception Handling with User Input

When the index is taken from user input, handling an IndexError ensures the program does not crash.


For better debugging, we can show last string index to the user along with exception.


Comment
Article Tags: