How to find the position of a substring with Python string index

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 functionality 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 illustrates 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 occurrence of the substring as the return value. So if a substring occurs more than once, all occurrences 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"))
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 occurrences 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 accordingly.

Tip

Processing strings is a popular task in Python programming. That’s why it’s important that strings are saved and output in an appropriate 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 alternative 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 difference, 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 beneficial 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 difference 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 programming 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 predetermined, 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 occurrence of the substring is found in the string, the number of occurrences is incremented, and the search is restarted. When the end of the string is reached, the entire number of occurrences is produced, and the program terminates.

Tip

Looking for a way to publish your web application quickly and easily? Then Deploy Now from IONOS is the perfect platform for you!

We use cookies on our website to provide you with the best possible user experience. By continuing to use our website or services, you agree to their use. More Information.