How to use the polymorphic operator “in”, the “find()”, and “count()” methods to search for a substring in Python

Let’s say that you want to search for a substring within a string object. Nothing easier. In Python, there is a polymorphic operator named in which allows you to do just that! Let’s try it!

>>> s1 = 'Dan is a web developer based within the EU.'
>>> 'Dan' in s1
True
>>> 'Dumitrache' in s1
False
>>> 'EU' in s1
True
>>> 'Canada' in s1
False

Basically, in allows you to find out if one element of data exists within a larger set of data elements. It returns a Boolean value of True if the searched element was found and False if the element was not found.

But, just telling you True or False might not be enough. What if you want to know where that element is within the larger set of data elements. No problem! You can use the find() method to find the location of a substring.

>>> s1.find('web')
9
>>> s1.find('Canada')
-1

We just found that the string “web” is at index 9. You know the position of the substring in the string but that substring can occur many times within the string. What if you want to know how many times a substring occurs in a string. That is also easy! You can use the count() method.

>>> s1 = 'This is a Honda and this is a Yamaha!'
>>> s1.count('th')
1
>>> s1.count('is')
4
>>> s1.count('a')
7

Leave a Reply