This article will show you how to check if a string contains another string in the Python programming language.
Python has several methods for accomplishing the same thing – read on for how to do it.
Using in to Check if A String Contains a String in Python
The fastest and best way to check if a string contains a value in Python is to use the in operator:
if "screw" in "hello linuxscrew!": print("Found!")
Or, to check if a string doesn’t contain a value:
if "screw" not in "hello linuxscrew!": print("Not found!")
Using *string.find() to Check if A String Contains a String in Python
The string type in Python also has a built-in method for finding the index of a substring within a string.
The find() method will return the index of the string if it is found, or -1 if it is not (the index is the position of the found substring – as indexes start counting at position 0, -1 is used to signal that it isn’t present).
myString = "hello linuxscrew!" if myString.find("screw") == -1: print("Not found!") else: print("Found!")
It’s recommended you use the first method to check whether your string contains a value – that’s what the in statement is made for. Using string.find(), and other string methods that may return a value that can be used to test for the substring may work, but it’s not their intended use.
It’s also worth noting that Python won’t care whether the string being searched is in a whole word or just part of one – searching for “oo” in “Food is eaten” will return TRUE.