How to Check if a Python String Contains a Substring — Codefather
--
Knowing how to check if a Python string contains a substring is a very common thing we do in our programs.
In how many ways can you do this check?
Python provides multiple ways to check if a string contains a substring. Some ways are: the in operator, the index method, the find method, the use of a regular expressions.
In this tutorial you will learn multiple ways to find out if a substring is part of a string. This will also give you the understanding of how to solve the same problem in multiple ways using Python.
Let’s get started!
In Operator to Check if a Python String Contains a Substring
The first option available in Python is the in operator.
>>> 'This' in 'This is a string'
True
>>> 'this' in 'This is a string'
False
>>>
As you can see the in operator returns True if the string on its left is part of the string on its right. Otherwise it returns False.
This expression can be used as part of an if else statement:
>>> if 'This' in 'This is a string':
... print('Substring found')
... else:
... print('Substring not found')
...
Substring found
To reverse the logic of this if else statement you can add the not operator.
>>> if 'This' not in 'This is a string':
... print('Substring not found')
... else:
... print('Substring found')
...
Substring found
You can also use the in operator to check if a Python list contains a specific item.
Index Method For Python Strings
I want to see how else I can find out if a substring is part of a string in Python.
One way to do that is by looking at the methods available for string data types in Python using the following command in the Python shell:
>>> help(str)
In the output of the help command you will see that one of the methods we can use to find out if a substring is part of a string is the index method.