Python - How To Check if a String Contains Word in Python

ID : 63

viewed : 151

Tags : PythonPython String

vote vote

100

This tutorial will introduce the method to find whether a specified word is inside a string variable or not in Python.

Check the String if It Contains a Word Through an if/in Statement in Python

If we want to check whether a given string contains a specified word in it or not, we can use the if/in statement in Python. The if/in statement returns True if the word is present in the string and False if the word is not in the string.

The following program snippet shows us how to use the if/in statement to determine whether a string contains a word or not:

string = "This contains a word" if "word" in string:     print("Found") else:     print("Not Found") 

Output:

Found 

We checked whether the string variable string contains the word word inside it or not with the if/in statement in the program above. This approach compares both strings character-wise; this means that it doesn’t compare whole words and can give us wrong answers, as demonstrated in the following example:

string = "This contains a word" if "is" in string:     print("Found") else:     print("Not Found") 

Output:

Found 

The output shows that the word is is present inside the string variable string. But, in reality, this is is just a part of the first word This in the string variable.

This problem has a simple solution. We can surround the word and the string variable with white spaces to just compare the whole word. The program below shows us how we can do that:

string = "This contains a word" if " is " in (" " + string + " "):     print("Found") else:     print("Not Found") 

Output:

Not Found 

In the code above, we used the same if/in statement, but we slightly altered it to compare only individual words. This time, the output shows no such word as is present inside the string variable.

  • Related HOW TO?