![]() |
VOOZH | about |
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].
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).
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.
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.