Python is one of the easiest programming languages to learn because of its simple syntax, yet it’s powerful for various uses. It can be utilized for automation, data visualization, data analysis, machine learning, and web and software development. No wonder, it’s often the first choice for budding programmers who want to learn coding on their own.
If you’re getting started on your Python journey but have been derailed by the “IndexError: string index out of range” error, then you might need a refresher on strings and indexing.
There are key points to remember when indexing, like starting from 0 and staying within the index’s range. If you try to choose an index value outside the index’s range, you will be greeted with the “IndexError: string index out of range.”
Continue reading to learn the basics of strings, indexing, and how to avoid the said error altogether, even when selecting characters from the beginning, middle, and end of a string.
What are Strings?
In Python, strings are immutable literals placed inside double or single quotes. Immutable means strings are unchangeable. When you set a variable as a string, that string cannot be changed once it’s created. You can use one of several operations if you need to construct a new string.
Here are some basics to help you get started with strings:
1. Creating a String and Assigning to a Variable
To create a new string, just put any combination of characters inside double or single quotes and set it equal to a variable:
>>> create_a_string = ‘this is your first string’
Once you’ve assigned a string to a variable, you can call print on that variable. You will see the string as an output:
>>> print(create_a_string) This is your first string
2. Adding Two Strings
If you have two string variables, you can combine these two variables, much like operations with numbers. This is also called concatenation:
>>> a = ‘Hello there’ >>> b = ‘ Tom’
Notice the space included before the word Tom. Now add them together and print the result:
>>> c = a + b >>> print(c) Hello there Tom
Introduction to Indexing
We’re going to cover some essential basics of indexing before moving on to fixing the “IndexError: string index out of range” error.
What are String elements?
A string is just a sequence of characters. Individual characters within a string are called string elements. These elements can be accessed by using an index. An index is a number that matches an element’s position within a string. Here’s a visual for the string ‘Python’:
‘P y t h o n’
0 1 2 3 4 5
In Python, the first character of any string has an index of 0. For each additional element, add +1 to find the index number. Square brackets are used to access string elements using index numbers. Here’s an example of how this works in practice:
>>> str = ‘name’ >>> print(str) n >>> print(str) e
What is an Index’s Range?
Every string can be indexed, but every index has a range. This is because a string is a discrete number of characters. A string’s index range is one less than its total number of characters because instead of starting at 1, indexing starts at 0 positions. A simple way to determine a string’s range is to subtract one from the total number of characters.
Here are a few examples of strings and their ranges:
alphabet = ‘abcdefghijklmnopqrstuvwxyz’
Alphabet has a range of 25 because there are 26 characters,
s = ‘sharks are scary’
S has a range of 15 because there are 16 characters (including 2 spaces).
What are Index Errors?
We can move on to cover index errors in greater detail now that you have a clearer understanding of the following topics:
- What are strings?
- Writing strings and assigning to variables
- String concatenation
- String elements
- What is indexing?
- Indexing syntax
- Index ranges
- Len() method
If you’ve jumped to this section in pursuit of answers, make sure you understand the topics listed before continuing with the rest of the guide. In Python, an ‘IndexError’ appears anytime you try to access an invalid index. Most often, this is from exceeding the index ranges.
What does “string index out of range” mean?
We’ve covered the basics of indexes and range, so now we can discuss the specific Index Error, the “string index out of range”. This message is printed when you’ve tried to call or use an index position that does not actually exist. To avoid this error, ensure you never exceed the index’s range.
How to Correctly Write String Operations Using Indexes
Say, you’ve encountered the “IndexError: string index out of range” and you now know this was caused by improperly calling an index position that is outside of the index’s range. Since we’ve established this is the root cause of this issue, we can now work on learning to correctly write string operations using indexes, so this error doesn’t appear again.
1. Using the len() Method
In our introduction to indexes, we showed you how to count characters and subtract 1 to find the range. This method works but isn’t a very effective use of time nor is it practical in actual programming situations. Instead, you can use Python’s built-in len() method. This method calculates the length of the string for you. Here’s an example:
>>> str = ‘executive producer’ >>>print(len(str)) 18
From the length, the index range is the length minus 1. So the range for this string is 17. This method lets you uncover the value of the range much more quickly than manually counting.
2. Selecting the First Characters
If you need to select one of the first characters in a string, it’s super easy. Just remember to start with position 0, not 1. It’s very easy to get your counting off by one because we are so used to counting from 1.
So the first three characters of our ‘executive producer’ string:
>>>print(str) e >>>print(str) x >>>print(str) e >>>print(str) c
3. Selecting the Middle Characters
If you need to select one of the middle characters in a string, you can use one of two options:
Bisect the Length
Suppose you’ve already determined the length of the ‘executive producer’ string. It is made up of 18 characters, so it has a range of 17. You can effectively half the length to select the middle characters of a string. In the case of our string:
18/2 = 9
Then subtract 1 to get the index value:
9 -1 = 8
When we use 8 as our index number, we get the following result:
This is the last e in executive, within the ‘executive producer’ string.
Use index() Method
If your string is too long or has multiple substrings or words within a single string, you may prefer to use the index() method to find an index value in the middle. This is great if you want to locate the index values for a specific word. Let’s create a new string and try this method out:
>>>new_string = ‘I really enjoy learning Python’
Now we’re going to use the index() method to target a specific word, or substring, within new_string. We want to find the index position of the word ‘learning’:
>>>learning_position = new_string.index(‘learning’)
When we print the learning_position variable, we get the lowest index where the substring ‘learning’ is found:
Once you find the index value you are looking for, you can carry out other operations. For example, you can select the entire word ‘learning’ by using indexing:
4. Selecting the Last Characters
If you need to select the end of a string, you can use negative numbers. Negative indexing starts from -1, not from 0. Suppose you want to select the last word in the new_string variable, Python. This word is 5 characters long. Here’s how you’d do this:
For a long string, it’s much easier to count from the end than to start at the beginning. You also don’t have to worry about getting confused by starting with 0. But remember to start from the more negative number, or your word will print in reverse.
Summarizing Python Strings and Indexing
Now that we’ve broken down the basics of strings and indexing, you should have a much firmer grasp on how to use Python strings and indexing when combined with string operations. An excellent foundation is essential to avoiding the common pitfalls of beginners like the “IndexError: string index out of range”.
You can manually count the string length, but using the len() method is the most preferable. From there, you can determine the index’s range by simply subtracting 1. If you never call or use an index over that value, you won’t trigger the ”IndexError: string index out of range.”
With that knowledge, you can start working with longer and longer strings and using more complex string operations. You can also target specific areas of a string, the beginning, middle, and end characters.