To check whether a String contains a substring:
Python has a built-in method called "in" that can be used to check if a string contains a substring. This method is case-sensitive, so you will need to make sure that the string and substring are both in the same case.
"Substring" in "String"
Here is an example of how to use the "in" method:
if "wor" in "hello world": print("matched") else: print("Not matched")
The code is checking if the string "wor" is found in the string "hello world". If it is found, it will print "matched". If it is not found, it will print "Not matched".
Python has a built-in find() method to check if a string contains a substring or not. This method returns the index of the substring if it is found, otherwise, it returns -1.
my_str = "Devsheet" my_substr = "sheet" if (my_str.find(my_substr) != -1): print("Found") else: print("Not found")
The above code example is looking for a substring within a string using the find() function. If the substring is found, it will print "Found". Otherwise, it will print "Not found".
A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. They can be used to search, edit, or manipulate text and data. The Python "re" module provides regular expression support.
Here, we will learn how to use the Python regex search() function to check if a string contains a substring using regular expressions. We will use the search() function to check if a substring exists in a string and return a Boolean True/False value.
from re import search full_string = "Devsheet" sub_string = "hee" if search(sub_string, full_string): print("Substring found") else: print("Substring not found")
The above python code example above uses the re module's search function to check if a substring is found in a given string. If the substring is found, the code prints "Substring found". Otherwise, if the substring is not found, the code prints "Substring not found".