Python string index out of range - How to fix IndexError
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
# Accessing an Index Beyond the String Length
s = 'GeeksforGeeks'
# string length is 13, so valid
# string index range is 0 to 12
print(s[13])
# access invalid negative index
# valid negative index range -1 to -13
print(s[-14])
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).
s = "GeeksforGeeks"
index = -14 # Invalid index
# condition for both +ve and -ve index
if -len(s) <= index < len(s):
print("Character at index:", s[index])
else:
print("Index out of range!")
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.
s = 'GeeksforGeeks'
# valid index range is 0 to 12
index = 13
try:
print("Character at index:", s[index])
except IndexError:
print("Index out of range!")
Exception Handling with User Input
When the index is taken from user input, handling an IndexError
ensures the program does not crash.
s = 'GeeksforGeeks'
index = int(input("Enter an index: "))
# Example: User enters 13 [which is invalid index]
try:
print("Character at index:", s[index])
except IndexError:
print("Index out of range! Please enter a valid index.")
For better debugging, we can show last string index to the user along with exception.
except IndexError:
last_valid_index = len(s) - 1
print(f"Error: The index {index} is out of range.")
print(f"Last valid index is {last_valid_index}, character: '{s[last_valid_index]}'.")