7 Different Ways To Check If String Contains Substring Python


In this article, you will see 7 different ways to check if string contains substring python.

A substring is a part of a string. For example, if we have a string "Hello World", then "World" is a substring of the string "Hello World".

A string in Python is a sequence of characters. It is created by placing characters between single quotes (') or double quotes (").

Let's see how to check if a string contains a substring in Python.

Check If String Contains Substring Python

    Table Of Contents

  1. Using find() function
  2. Using index() function
  3. Using in operator
  4. Using count() function
  5. Using startswith() function
  6. Using re.search() method
  7. Using re.findall() method

1. Using find() function

The find() is a built-in function in Python that is used to find the first occurrence of the specified value in a string..

Using this you can check for a substring in a string. It returns the index of the first occurrence of the substring in the string. If the substring is not found, it returns -1.

Syntax

str.find(substr, start, end)

The find() function is called on a string and the substring to be searched for is passed as an argument. You can also pass the starting index and the ending index in the argument but it is optional.

The following example checks a substring in a string using the find() function.

str = "First learn then earn"

# find "earn" in str
print(str.find("earn"))

Output

7

In the above example, the find() function searches for "earn" and return the first index which is 7 in the string.

Searching for something which is not in the string. It returns -1.

str = "First learn then earn"
# find "cat" in str
print(str.find("cat")) # -1

Output

-1

2. Using index() function

The index() is another Python function that can be used to search for a substring in a string.

Just like the find() function, the index() function returns the index of the first occurrence of the substring in the string.

The only difference between the index() and find() function is that the index() function raises an error if the substring is not found.

Syntax

str.index(substr, start, end)

Let's check for a substring in a string using the index() function.

str = "First learn then earn"

# using index() function
print(str.index("earn"))

Output

7

As we know that index() function raises an error if the substring is not found. So for our program to run successfully, we need to handle the error.

The following example shows how to handle the error using the index() function.

str = "First learn then earn"

# using index() function safely
try:
    print(str.index("cat"))
except ValueError:
    print("Substring not found")

Output

Substring not found

3. Using in operator

The in operator is a Python keyword. It is used to check if any given element is present in a sequence.

you can take advantage of this operator to check if a substring is present in a string.

Syntax

substr in str

Using the in operator to find a substring in a string.

str = "First learn then earn"

# check if string contains substring python
if "earn" in str:
    print("Substring found")

Output

Substring found

4. Using count() function

The count() function counts a number of non-overlapping occurrences of a substring in a string. It returns the number of occurrences of the substring in the string.

It can be used to check if the string contains a substring. If the return value is greater than 0, then the substring is present in the string.

Syntax

str.count(substr, start, end)

The following example shows how to use the count() function to check if a substring is present in a string.

str = "First learn then earn"

# using count() function
if str.count("earn") > 0:
    print("Substring is present in the string")
else:
    print("Substring is not present in the string")

Output

Substring is present in the string

5. Using startswith() functions

The startswith() function checks if a string starts with a specified substring. This can't directly tell if a substring is present in string or not but you can loop through the string and check if the substring is present at each index.

This way if the substring is present at any index then it will return True.

Here is a simple implementation of this concept.

str = "First learn then earn"

# using startswith()
# to find the substring in the string
found = False
for i in range(len(str)):
    if str.startswith("cat", i):
        found = True
        print("Found at index", i)
        break

if not found:
    print("Substring Not found")

Output

Found at index 7

6. Using re.search() function

The regular expression provides a more powerful way to search within a string. The re module provides re.search() function which can be used to search for a substring in a string.

The re.search() function returns a Match object if the substring is found in the string. If the substring is not found, then it returns None.

The following example shows how to use re.search() function to search for a substring in a string.

from re import search
str = "First learn then earn"

# searching for the substring
if search("earn", str):
    print("Substring found")
else:
    print("Substring not found")

Output

Substring found

7. Using re.findall() function

The re.findall() method is another powerful method that comes with the re module. It returns a list of all the substrings that match the given pattern.

Create a program that checks the length of returning list from re.findall() method, if the list is empty then the substring is not present in the string and if the list is not empty then the substring is present in the string.

from re import findall
str = "First learn then earn"

# findall returns a list of all match
if len(findall("earn", str)) == 0:
    print("Substring not found")
else:
    print("Substring found")

Output

Substring found

Conclusion

In this brief tutorial, you have learned to check if string contains substring in Python using 7 different methods.

Some of the methods are direct and some are derived from using other methods. Use any of them as your need.