How to check if a word exists in a string or not in Python
In this tutorial, we learn how to check if a word exists in a string or not in Python.
The string is an array, it is a datatype use in programming.string is used to store a sequence of characters. The string can be initialized in different ways.
Well, in this article, I am going to give you two ways to do this task. Using any one of the methods can easily check if a word or string part exists in the given string or not.
Using the contain method ‘contains()’
Let’s look at this example where we will ask the user to input both the strings and check if the first string contains second or not.
First=input("Enter first string:") Second=input("Enter second string:") print(First.__contains__(Second))
Enter first string: football
Enter second string:b
As we can see we ask the user to input the string and using (__contains__) method, if the First string contains Second string then it prints True, Otherwise False.
Using ‘in’ operator in Python
The easiest way is via ‘in’ operator in Python.
The operator is shorthand for calling an object’s and also work well for checking and object exists or not.
Let’s take a look at this example.
A="Stack Abuse" B="a" if B in A: print("Found!") else: print("Not found!")
As you can see, the ‘in’ operator returns Found! when the substring exists in the string.
Otherwise, it returns Not found!.
A=string and B=substring