Jump to content

How to Find a Substring in Python?

Linux Hint

Recommended Posts

Substring” is commonly known as a small contagious sequence or part of characters within a string. In computing, we users can perform multiple operations on a substring including searching, extraction, and manipulation. In Python searching is used to perform text processing from which the user finds a substring from a large sequence. It can be performed using multiple built-in functions/methods.

In this tutorial, we will look at various functions, operators, and expressions for finding substrings in Python.

How to Find a Substring in Python?

To obtain the element of a substring from the specific data, the below-listed approaches are used in Python:

Now, go ahead and implement each of the aforementioned methods in Python one by one!

Example 1: Find the Substring in Python Using the “in” Operator

The most effective way to find if an input string contains a substring is by utilizing the “if … in” statements, it will return “True” if the required substring is detected otherwise, it will return “False”. Here is an illustration:

Initially, we declared and initialized a string variable “mystring” as the “Welcome to Linux-Hint!“. Then, declared a variable named “substring” that contains the substring value as “Linux” which we want to find from the above-given string. After that, we used the “if … in” statement to determine whether the provided substring “Linux” exists in the input string or not. Lastly, applied the “print()” method to display the message on the console:

mystring = "Welcome to Linux-Hint!"
substring = "Linux"
if substring in mystring:
    print("Successfully found the substring!")

According to the below-given output, we have successfully found the substring:


Example 2: Find the Substring in Python Using the “find()” Method

Another way to find the index of the initial instance of a substring inside a string, the “find()” method is used. If the specified substring is found it will return to show the message, otherwise, it will return “-1”.

Check out the provided examples for practical demonstration!

We used the previously declared “mystring” and “substring” string variables. Here, the “mystring” represents the input string, and the “substring” holds the required substring value, respectively. Then, we invoked the “find()” method and pass it a “substring” variable as an argument. The outcomes from this method will be saved in the “index” variable. After that, used the “if” statement that determines if the substring is not found, then return the “-1”. Otherwise, it will show the index of the initial instance of the substring within the input string. Lastly, applied the “print()” method that takes the “index” variable:

index = mystring.find(substring)
if index != -1:
    print("The Substring found at index:", index)

The below output indicates that the index of the initial instance of the substring has been found successfully:


Example 3: Find the Substring in Python Using the “index()” Method

Another built-in method in Python for finding the substring is “index()”. It returns the index value of the first instance of the specified substring from an input string. If the substring is not found, it will throw a ValueError rather than returning -1.

Let’s move toward the below-given example!

Here, we used the previously declared string and substring variable values. Then, used the “try” block to deal with any errors that might occur. Inside this block, we used the “index()” method to find the position of the first element of the given substring. If the substring is located inside the input string, the code will run without any exception. Otherwise, except code block will be executed and throw a “ValueError” error that will serve to catch and handle this exception:

mystring = "Welcome to Linux-Hint!"
substring = "Linux"
    index = mystring.index(substring)
    print("The given substring found at index", index)
except ValueError:
    print("The given substring not found!")



Example 4: Find the Substring in Python Using “Regular Expressions”

In Python, the “re” module can be used for finding substrings with patterns. For that purpose, first, import the “re” module. Then, represent the input string from which we want to search for a substring. After that, use the “re.compile()” method to compile the regular expression pattern. Now, the value of the “sub_string” variable will serve as the pattern and pass it to the “pattern” variable. Next, we utilized the “search()” method that will take the given string as a parameter and search the substring from it. If any match finds, the code block in the “if” statement will be executed and output will be displayed through the “print()” method:

import re
mystring = "Welcome to Linux-Hint!"
sub_string = "Linux"
pattern = re.compile(sub_string)
match = pattern.search(mystring)
if match:
    print("Successfully found substring!")

The below output shows that the match has been found successfully:


That’s all! We have demonstrated several methods for finding substrings in Python.


A substring is a part of characters within a string. In Python, finding substrings is possible by utilizing the multiple built-in functions, methods, and operations including “find()”, “index()”, and regular expressions. In this guide, we have described different methods in Python for finding a substring.

View the full article

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...