Python’s index() method can be used to search a string and retrieve the index of a Python substring. You can either search the whole Python string or only a part of it.

Syntax and func­tion­al­i­ty of the Python string index

The syntax of the index method is very easy to explain. The method can be invoked with one, two, or three arguments, with the last two being optional. The first argument is always the substring, after which you can review the string. The two optional arguments are the indexes at which the search should be started or stopped. You can use these if you’re only searching a certain area of the string for the substring. The following code snippet il­lus­trates the syntax of this method:

string.index(substring)
string.index(substring, start, end)
Python

In this example, string is an arbitrary string and substring is the substring to search for. start and end indicate the start and end indices of the search. If no end index is specified (if you have only two arguments in total), the search ends at the end of the string. The method returns the index of the first oc­cur­rence of the substring as the return value. So if a substring occurs more than once, all oc­cur­rences after the first one are ignored by index(). Here’s an example of how the method works.

string = "I am a string"
print(string.index("String"))
# output: 12
print(string.index("in"))
# output: 5 (the "a" in "am")
print(string.index("in", 7, len(string) - 1))
# output: 9 (the "ing" in "string")
print(string.index("in", 7))
# output: 9 (the "ing" in "string")
print(string.index("Python"))
# Exception-error message: ValueError
Python

As you can see in the example above, the second index() call returns only the index of the “a” in “am”. Other oc­cur­rences of “am” are ignored. In the last call of index() you can see that the method returns a ValueError exception if the substring isn’t included. This exception also appears if negative indexes are entered or if the start index is greater than the end index. If one of these cases is possible in your program, you can handle the exception ac­cord­ing­ly.

Tip

Pro­cess­ing strings is a popular task in Python pro­gram­ming. That’s why it’s important that strings are saved and output in an ap­pro­pri­ate format. In our article on Python string formats we take a closer look at how you can adapt the format of the strings to your needs.

An al­ter­na­tive is the find method

Depending on what you need the index method for, the find method might be a better choice. It’s almost identical to the index method, with one important dif­fer­ence, which is that if the substring isn’t found, no exception is created. Instead, it simply returns -1. Since an unhandled exception would cause your program to crash, this can be very ben­e­fi­cial if you can’t or don’t want to handle a possible exception. The handling of the exception can even be simulated with an if condition, as shown here:

string = "Python"
if(string.find("Py") != -1):
    print("Substring included! Index: ", string.find("Py"))
else:
    print("Substring not included!")
Python

In this example, if the substring isn’t found, there is a branch, just like when handling an exception. The biggest dif­fer­ence is that find() in this example has to be executed multiple times when the substring is found.

Tip

Python is one of the most flexible pro­gram­ming languages out there. This gives you a lot of options in terms of what you can perform on strings. Find out more in our article on different ways to [compare Python strings.

Python string index examples

Now we’ll look at two examples of how index() can be used in a program. First, we’ll look at a simple example, then a slightly more complex one.

string = "Peter Piper picked a peck of pickled peppers."
print("The string to check is ", string)
while(True):
    sub = input("substring input: ")
    try:
        print("the index is: ", string.index(sub))
    except:
        print("The substring is not included :/")
Python

This example searches for a substring in a string. It then outputs whether the substring is contained in the string and, if so, at which index. In this case, the string we’re searching is pre­de­ter­mined, but the substring is re-entered by the user each time.

def try_except(start):
    try:
        return string.index(sub, start)
    except:
        return -1
string = input("string input: ")
sub = input("substring input: ")
occur = 0
start = 0
while(try_except(start) != -1):
    start = try_except(start) + len(sub)
    occur = occur + 1
print("Occur: ", occur)
Python

In this example, a string entered by the user is checked for a substring. If an oc­cur­rence of the substring is found in the string, the number of oc­cur­rences is in­cre­ment­ed, and the search is restarted. When the end of the string is reached, the entire number of oc­cur­rences is produced, and the program ter­mi­nates.

Tip

Looking for a way to publish your web ap­pli­ca­tion quickly and easily? Then Deploy Now from IONOS is the perfect platform for you!

Go to Main Menu