Summary: In this post, we will learn how to check if a string contains a substring in python.

Example:

There are multiple ways to multiple ways to check if a Python string contains a substring. Let’s discuss each method with examples.

Method 1: Using in Operator

Python in operator returns true if a string contains another string as a substring. It is the easiest way to check for a substring in python.

Here is the python example using in operator to check if string contains substring.

output

Found

The in operator functions similar to __contains__ method, it can also be used to check for items in data structures like list.

Method 2: Using find() method

find() method in Python can be used for checking if a string contains a substring.

It returns the index position of the first letter of the substring present in the string otherwise returns -1.

The general syntax for find method is

Here is an Python example using the find() method:

output

Found

Method 3: Using index() method

index() is another Python string class method that can be used to find the index of the first occurrence of a substring in the given string.

It is a little different from the find() method. If the substring is not present in the string then it throws a ValueError, which needs to be handled using Python try and except.

The general syntax for index method is

Here is an Python example using the index() method:

output

Found

If you don’t want to handle any exception then use find() method instead of index().

Method 4: Using count() method

count() is another method in python of type string which returns the count of a substring in the string i.e. number of occurrences of a substring in the string.

It returns 0 if the substring is not found.

The syntax for the count method is

Python example using the count() method:

output

Found

count() method is useful for knowing the number of occurrences of the substring in the parent string.

Method 5: Using REGEX

REGEX (Regular Expression) provides a more flexible way to search for patterns or substring in the string.

In REGEX, We first define the pattern or substring as a string, and then we search the pattern in the parent string using search() method.

search() method comes as a part of a python builtin module called re. So in order to use this method we have to import re module.

The syntax for the search() method is

output

Found

It is recommended to use REGEX when we intend to do complex operation on strings, as it is slower than all the methods which we have discussed in this post.

In this tutorial, we learned multiple ways to check if a string in python contains another string as a substring.

Leave a Reply