Python: How to check if string contains substring
By Parth Patel on Mar 06, 2020
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.
substring in string
>>> 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.
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')
3) Use "find" function
find function is the another method which can be used to check whether string contains any substring or not. If it does, then it will return the index of the first character of the substring in the string (where string is considered as array of characters). Thus
find function is also or rather mainly used to find the index of the substring or character.
>>> sr = "My first string is love" >>> sub = "love" >>> sr.find("first") 3
Apart from these, you can also use count function, or going basic - use brute method to check whether string contains substring in python. I hope this helped you.