Here are 2 ways to check if a substring exists in a string in Python:
(1) Using the “in” keyword:
my_string = "This is an example of a string" my_substring = "example" if my_substring in my_string: print("Substring found") else: print("Substring not found")
The result:
Substring found
(2) Using the “find()” method:
my_string = "This is an example of a string" my_substring = "example" if my_string.find(my_substring) != -1: print("Substring found") else: print("Substring not found")
The result:
Substring found
Note that the “!= -1” means that if the result of the “find()” method is different from -1, the substring is actually found. Else, when the “find()” method returns -1, the substring is not found.
Examples of Substrings Not Found
(1) Using the “in” keyword:
my_string = "This is an example of a string" my_substring = "hello" if my_substring in my_string: print("Substring found") else: print("Substring not found")
The result:
Substring not found
(2) Using the “find()” method:
my_string = "This is an example of a string" my_substring = "hello" if my_string.find(my_substring) != -1: print("Substring found") else: print("Substring not found")
The result:
Substring not found