In this post, we will discuss multiple ways to check if a string contains a substring in python.

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. It can be used as follow.

output

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

Method 2: Using find() method

find() method of type string in python is used for checking if a string contains a substring. If yes, then it returns the index position of the first letter of the substring in the string otherwise it returns -1.

The general syntax for find method is

output

Method 3: Using index() method

There is another method of type string in python called index() used to find the index of the first occurrence of substring in the string. It is little different from find() method because if the substring is not found in the string then it throws a ValueError which needs to be handled using try and except.

The general syntax for index method is

output

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

output

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 in the form of 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 import it before using it in the program.

The syntax for the search method is

output

Use REGEX when you intend to more complex operation on strings. It is slower than all the mentioned methods for substring check.

I hope you understood the program part to check for substring in a string. If you have any doubts or suggestions then please comment below.

Leave a Reply