Check if String contains a Substring in Python

If you are new to programming or are coming from a programming language other than Python, you may be searching for the best way to determine if a Python string includes another string. There are several different methods to do this in Python.

In this article, I will discuss all of the common methods for checking if a String contains another String in Python.

Before diving into these methods, it is important to understand the following information so that you can choose the appropriate method for your needs:

  • Do you only need a Boolean Value (True/False) in return?
  • Do you need the index of where the match starts?
  • Do you need the number of occurrences of the substring?

Note: All the methods of the string containing substring are case-sensitive. So, if you want to have a case-insensitive search then you will have to use lower() or upper() methods on both the string and the substring.

1. The in Operator

The easiest way to check if a Python string contains a substring is to use the in operator.

In Python, in and not in are the membership operators. They are used to test whether a value or variable is found in a sequence. It can be String, List, Tuple, Set, or Dictionary. The Python inreturns a Boolean (either True or False). To check if a string contains a substring in Python using the in operator, we simply invoke it on the superstring.

Example 1

superstring = "appsdeveloperblog"
substring = "developer"

val = substring in superstring

print("This is a boolean value the in operator returns: ", val) #here it will print "True"
print("This is type of the value the in operator returns: ", type(val)) # return <class 'bool'> i.e. boolean
if val:
    print("Found!")
else:
    print("Not found!")

#For caase-insensitive search 
val = substring.lower() in fullstring.lower()
print("Case insensitive: ", val)

Note that the Sentence case of the word is the same in the superstring and also in the substring. If there was a difference, it would have been false.  I have added the code for case-insensitive search too. If you are dealing with unknown String values, then use that code

Output

This is a boolean value the in operator returns:  True
This is type of the value the in operator returns:  <class 'bool'>
Found!
Case insensitive: True

Note that Python considers an empty string as a Substring of any String. So the following will always give True. If you do not want that, then you will have to check the length of the substring before matching it with the superstring.

Example 2

superstring = "appsdeveloperblog"
substring = ""

print("Original Value: " , substring in superstring)

if (len(substring) == 0):
    print("Empty SubString")
else: 
    print(substring in superstring)

Output:

Original Value:  True
Empty SubString

In the first instance of using the “in” operator, the program checks if the empty substring is present in the superstring. Since an empty string is a substring of any string, the result will be True if the substring is empty and False otherwise.

In the second instance of using the “in” operator, the program checks if the substring is present in the superstring. If the substring is not empty, this will check if the characters in the substring appear in the same order and next to each other within the superstring.

For example, if the substring was “developer”, the program would check if the characters “d”, “e”, “v”, “e”, “l”, “o”, “p”, and “e” are present in the superstring in that order and next to each other.

If the substring is found in the superstring, the “in” operator will return True, and if it is not found, it will return False.

2. The String.index() Method

The String type in Python has a method called index() . This can be used to find the starting index of the first occurrence of a substring in a string. It will not work with multiple occurrences.

It returns the index if the substring is found. If the substring is not found, a ValueError exception is thrown, which can be handled with a try-except block.

Example

superstring = "appsdeveloperblog"
substring = "developer"
try:
    idx = superstring.index(substring)
    print("Found at index ", idx)
except ValueError:
    print("Not found!")

Output

Found at index  4

In the given code, the index() method is used to find the index of the substring “developer” within the superstring “appsdeveloperblog”. The index() method is called on the superstring and is passed the substring as an argument.

If the substring is found within the superstring, the index() method returns the index of the first occurrence of the substring within the superstring. This index value is assigned to a variable called idx.

The program then prints a message stating that the substring was found at the index value of idx.

However, if the substring is not found within the superstring, the index() method will raise a ValueError exception. To handle this exception, the code is wrapped in a try/except block. If a ValueError exception is raised, the program will print a message stating that the substring was not found within the superstring.

3. The String.find() Method

The String class has another method called find() which is more convenient to use than index(), because it does not through an exception if the substring does not match. So you do not need to worry about handling exceptions.

If find() doesn’t find a match, it returns -1. Otherwise, it returns the left-most index of the substring in the superstring.

Example

superstring = "appsdeveloperblog"
substring = "developer"
idx = superstring.find(substring)
if idx == -1:
    print("Not found!")
else:
    print("Found at index ", idx)

Output

Found at index  4

In the given code, the find() method is used to find the index of the substring “developer” within the superstring “appsdeveloperblog”. The find() method is called on the superstring and is passed the substring as an argument.

If the substring is found within the superstring, the find() method returns the index of the first occurrence of the substring within the superstring. This index value is assigned to a variable called idx.

However, if the substring is not found within the superstring, the find() method returns a value of -1. Therefore, the program checks if the value of idx is -1. If idx is -1, the program prints a message stating that the substring was not found within the superstring.

On the other hand, if idx is not -1, it means that the substring was found within the superstring. The program then prints a message stating that the substring was found at the index value of idx.

4. The String.__contains__() Method

Python String class has __contains__() function that we can use to check if it contains another string or not. It is similar to in operator and returns a Boolean value. But mostly, the in operator is preferred over __contains__(). Firstly because it seems complex. If someone else is viewing your code, he will get confused at first glance. Secondly, it takes longer than in.

Example

superstring = "appsdeveloperblog"
substring = "developer"
bol_val = superstring.__contains__(substring)
if bol_val:
    print("Found!")
else:
    print("Not Found!")

Output

Found!

In Python, the “in” operator is generally used to check whether a string contains a substring. However, in the given code, the __contains__() method is used to perform the same check.

The __contains__() method is an inbuilt method in Python that checks whether a given value is present in a sequence. It can be used to check whether a substring is present in a larger string.

In the given code, the __contains__() method is called on the superstring with the substring as an argument. The method returns a boolean value, True if the substring is present in the superstring, and False otherwise.

The program then checks the value of bol_val. If bol_val is True, it means that the substring was found within the superstring. The program prints a message stating that the substring was found.

On the other hand, if bol_val is False, it means that the substring was not found within the superstring. The program prints a message stating that the substring was not found.

Execution Time

If you are dealing with large data sets and you are looking for the fastest from the above-mentioned methods. Following is the summary of each method with its execution time. See which one works for you best.

python string contains substring

Conclusion

That concludes this tutorial. I hope it was helpful to you. If you have any questions, please leave them in the comments section. If you would like more detailed tutorials on these methods, please let me know, and I would be happy to help. Additionally, please check out our Python tutorials page, where we regularly post content for both beginners and advanced developers. You’re sure to find something interesting there.