Progress

Check Python String contains another Substring

Check Python String contains another Substring

Solving problems in python takes the least amount of time as we have internal libraries to do all heavy lifting in the background. This also applies to check if Python string contains another substring or not.

There are multiple ways to do that. But here we will discuss some of the easiest and most used ways to find substring inside another string in Python.

Using in Operator

The in operator in python comes under the category of membership operator.

Members operators are helpful in checking if an object contains a sequence or not.

We can use the in operator in python to check if any string contains a particular substring or not.

Copy
"Coders" in "HolyCoders"
Output
True

From the above example, we can see that in operator effectively find a substring in any string.

Using the index method of Python String

The string.index()method is helpful in finding a substring in many cases. If you want to check the presence of substring as well as its position in that string then you must try this.

Copy
"HolyCoders".index("Coders")

#This lines gives error
"HolyCoders".index("programmer")
Output
>>> 4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

It returns the starting index of a substring in a string (space and tabs included in counting the index). If the substring is not present then ValueError is raised, remember to use try-except block.

Using the find method of Python String

The find method of python string is similar to the index method with one difference that it returns -1 when the element is not found while the index method throws ValueError.

It can be used in the case you don’t want to use try-except block while solving the problem.

Copy
"HolyCoders".index("Coders")

"HolyCoders".index("programmer")
Output
4
-1

These were some of the most common ways to find substring in python. Choose what best suits your needs according to the problem. In most cases, the in operator will do the work but in some problems, you will need either index or find method of strings in python

You may also Like:

Find Square root in Python

Share the Post ;)

Related Posts