In this code tidbit, we will discuss how to check if string contains substring in python. We will be using Python 3 for this tutorial. [Update your python to python 3 if you haven’t done so!!]

There are various ways to check if string contains another string in python. Here, I will show 3 such methods:

1) Use “in” operator

The “in” operator is the easiest method to find whether substring exists in string or not.

Syntax:

substring in string

Example:

>>> sr = "My first string is love"
>>> "first" in sr
True

2) Use contains function

In python, there are various magic methods and contains is one of them which can also be used to check whether string contains substring or not. Though I would recommend using “in” operator but this method still works well. Note that: It is case sensitive.

Syntax:

string.__contains__(substring)

Example:

sr = "My first string is love"
sr.__contains__("first")

#You can also call str class directly to use this method.
str.__contains__('My first string is love', 'first') 

#python #programming

Python: How to check if string contains substring
2.40 GEEK