string index out of range in Python

In this tutorial, I will explain the common “String Index Out of Range” error in Python, why it occurs, and how to fix it.

I will show here different scenarios where you might receive the error and how to fix it.

indexerror: string index out of range

The String Index Out of Range error occurs when you try to access a character in a string using an index that doesn’t exist. This typically happens when you attempt to access an index that is greater than or equal to the length of the string, or when you use a negative index that points before the start of the string.

Now, let me show you a few scenarios where you might receive this and how to fix it.

1. Accessing an Index Beyond the String Length

One of the most common causes of this error in Python is trying to access an index that is greater than or equal to the string’s length. Remember, Python uses zero-based indexing, so the last valid index is always one less than the string’s length.

Let me show you an example:

state = "California"
print(state[10])  # This will raise an IndexError

In this case, “California” has 10 characters, so the valid indices are 0 through 9. Trying to access index 10 will result in an error.

As you can see in the screenshot below, it gave me an error message stating, “IndexError: string index out of range.”

string index out of range python

Solution: Always ensure that your index is within the valid range. You can use the len() function to check the string’s length; here is how to fix it.

state = "California"
if len(state) > 10:
    print(state[10])
else:
    print("Index out of range")

Check out syntaxerror return outside function error in Python

2. Using an Empty String

Another common scenario is when you’re working with an empty string. Any attempt to access an index of an empty string will result in this error.

Let me show you an example.

Example:

user_input = input("Enter a US state: ")
print(user_input[0])  # This will raise an IndexError if the input is empty

Solution: Always check if the string is empty before trying to access its characters:

user_input = input("Enter a US state: ")
if user_input:
    print(user_input[0])
else:
    print("No input provided")

This is another way to fix indexerror string index out of range error in Python.

3. Iterating Beyond String Length

When looping through a string, it’s easy to iterate beyond its length accidentally. In that scenario, you will receive the indexerror: string index out of range in Python.

Example:

city = "New York"
for i in range(len(city) + 1):  # This will cause an error on the last iteration
    print(city[i])

Here is the exact output with the error message you can see:

indexerror: string index out of range

Solution: Ensure your loop doesn’t exceed the string’s length to fix this issue.

city = "New York"
for i in range(len(city)):
    print(city[i])

This is another way to fix the error string index out of range in Python.

Check out Command errored out with exit status 1 in Python

Best Practices to Avoid String Index Out of Range Error

  1. Always check the length of your string before accessing an index.
  2. Use string slicing instead of individual character access when possible, as it’s more forgiving with out-of-range indices.
  3. When iterating, prefer using for char in string: instead of indexing, as it automatically handles the string length.
  4. Use try-except blocks to handle potential IndexErrors gracefully.

Conclusion

Remember, Python’s string indexing starts at 0 and goes up to len(string) – 1. Remembering this will help you avoid many index-related errors in your Python programs. In this tutorial, I explained how to fix the error “string index out of range in Python“.

You may also like:

1 thought on “string index out of range in Python”

  1. Very well written andd done my friend!
    I’ve only just begun writing a blog myself inn the past few weeks and realised that
    lot of articles simply rehash old ideas but add verfy little of value.
    It’s fantastic to see an enlighteninng post oof some actual value to me.

    It’s going down onn my lis of details I need to emulate
    as a new blogger. Visitor eengagement and content quality are king.

    Some wonderful thoughts; yoou havve certainly made it on my list of sites
    to watch!

    Continue the excellent work!
    Cheers,
    Tandie

Comments are closed.

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.