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 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 given 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

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

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

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!

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.