How to fix IndexError: string index out of range
Strings are an essential part of just about any programming language. A string is an array of characters . The string index out of range means that the index you are trying to access does not exist. In a string, that means you're trying to get a character from the string at a given point. If that given point does not exist , then you will be trying to get a character that is not inside of the string.
Let's take the above example:
try following code:
But what happens if we request index 14?
Here we get a string index out of range , because we are asking for something that doesn't exist. In Python, a string is a single-dimensional array of characters. Indexes in Python programming start at 0. This means that the maximum index for any string will always be length-1 . Here that makes your numbers fail because the requested index is bigger than the length of the string.
The string index out of range problem has to do with a very common beginner problem when accessing elements of a string using its index. There are several ways to account for this. Knowing the length of your string could certainly help you to avoid going over the index.
When you run len() function on "numbers" you get the length of our string as 8. Just note that the length doesn't start at 0, it starts at 1. Since Python uses zero-based indexing , the maximum index of a string is the length of the string minus one. So, you can access the maximum index value of a string is its length minus one .
Handling errors and exceptions is another topic in itself, but here briefly show how to prevent it with string indices.
In the above example, the error handled it carefully .