Python string index out of range - How to fix IndexError
Last Updated :
17 Nov, 2024
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
Python
# 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).
Python
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.
Python
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.
Python
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.
Python
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]}'.")
Similar Reads
How to Fix IndexError - List Index Out of Range in Python IndexError: list index out of range is a common error in Python when working with lists. This error happens when we try to access an index that does not exist in the list. This article will explore the causes of this error, how to fix it and best practices for avoiding it.Example:Pythona = [1, 2, 3]
3 min read
Python Indexerror: list assignment index out of range Solution In Python, the IndexError: list assignment index out of range occurs when we try to assign a value to an index that exceeds the current bounds of the list. Since lists are dynamically sized and zero-indexed, it's important to ensure the index exists within the list's range before modifying it. Under
2 min read
Python | range() does not return an iterator range() : Python range function generates a list of numbers which are generally used in many situation for iteration as in for loop or in many other cases. In python range objects are not iterators. range is a class of a list of immutable objects. The iteration behavior of range is similar to iterat
2 min read
How to Fix "NameError: name 'os' is not defined" in Python If we are working with Python and encounter an error that says "NameError: name 'os' is not defined", then we need not worry, it is a very common issue, and fixing this error is very simple. This error usually occurs when we try to use the os module without importing it first. In this article, we wi
3 min read
How to Fix: KeyError in Pandas Pandas KeyError occurs when you try to access a column or row label in a DataFrame that doesnât exist. This error often results from misspelled labels, unwanted spaces, or case mismatches. This article covers common causes of KeyError in pandas and how to fix them.1. Column name not foundWhen workin
4 min read
Python - Returning index of a sorted list We are given a list we need to return the index of a element in a sorted list. For example, we are having a list li = [1, 2, 4, 5, 6] we need to find the index of element 4 so that it should return the index which is 2 in this case.Using bisect_left from bisect modulebisect_left() function from bise
3 min read