AppDividend
Latest Code Tutorials

How to Check if Python String Contains Another String | Python in Operator

0

In this tutorial, we will see How to Check if Python String Contains Another String. Python String class has one private method called __contains__(). It is not suitable for many instances, that is why we will see the other solutions. If it’s just a substring search, you can use the Python String find() method. The second way is to use Python In Operator. We will see one by one method in this tutorial.

Check if Python String Contains Another String

Now, we will talk about the first method, which is a Python String find() method.

Using find() Method

Python String find() function returns the integer. This integer is essentially an index of the beginning of a substring if a substring exists; otherwise -1 is returned.

See the following example.

# app.py

strA = "Game of Thrones was the best show on the planet"
print(strA.find("Thrones"))
print(strA.find("Breaking Bad"))

See the following output.

Check if Python String Contains Another String

 

Python find() method accepts a start index and an end index to limit your search within. See the following example.

# app.py

strA = "Game of Thrones was the best show on the planet"
print(strA.find("Thrones", 7, 15))

See the output.

Python String find() Example

 

Using the in operator

The operators in and not in test for membership. The X in S evaluates to True if X is a member of S, and False otherwise. The X in S returns the negation of X in S. All built-in sequences and set types to support this as well as a dictionary, for which in tests whether the dictionary has a given key. 

Let’s see the following example.

# app.py

strA = "Game of Thrones was the best show on the planet"
print("Thrones" in strA)

See the following output.

Using the in operator

 

As you can see, an in operator returns the True value when the substring exists in the string. Otherwise, it returns false. The above approach is very straightforward, clean, readable, and idiomatic.

Let’s see the in operator in if..else condition. See the below code.

# app.py

strA = "Game of Thrones was the best show on the planet"
if "Thrones" in strA: 
    print('It exists')
else:
    print('Does not exist')

See the below output.

in operator in if..else

 

Now, let’s see a not in operator in Python.

# app.py

strA = "Game of Thrones was the best show on the planet"
if "Breking Bad" not in strA: 
    print('Breaking Bad is not exist in the String.')
else:
    print('It exists.')

See the below output.

not in operator in Python.

 

So, in this article, we have seen the find() method and operators like in operator and not in operator in Python.

Finally, Python in and not in Operator tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.