A substring is a sequence of characters within a String. The following are the methods in Python to check if a string contains another string i.e. substring.
- By using
find()
method - By using
in
operator - By using
count()
method - By using
str.index()
method - By using
operator.contains()
method
Method 1: By using find() method
The method find() checks whether a string contains a particular substring or not. If the string contains that particular substring, the method returns the starting index of the substring else it returns -1.
Syntax: string.find(substring)
Example: Checking for the presence of substring within the string using find() method
str="Safa Mulani is a student of Engineering discipline."
sub1="Safa"
sub2="Engineering"
print(str.find(substring1))
print(str.find(substring2))
Output:
0
28
Method 2: By using in operator
The in
operator checks for the presence of substring within a string, if the substring is present it returns TRUE else it returns FALSE.
Syntax: substring in string_object
Example: Checking for the presence of substring within the string using in operator
str="Safa Mulani is a student of Engineering discipline."
sub1="Safa"
sub2="Done"
print(sub1 in str)
print(sub2 in str)
Output:
True
False
Method 3: By using count() method
The count() method checks for the occurrence of substring in a string. If the substring is not found in the string, it returns 0.
Syntax: string.count(substring)
Example: Checking for the presence of substring within a string using count() method
str="Safa Mulani is a student of Engineering discipline."
sub1="Safa"
sub2="student"
sub3="Done"
print(str.count(sub1))
print(str.count(sub2))
print(str.count(sub3))
Output:
1
1
0
Method 4: By using index() method
The method checks for the presence of a substring in a string. If the substring is not present in the string then it doesn’t return any value, rather it generates a ValueError.
Syntax: string.index(substring)
Example: Checking for the presence of a substring in a string using the index() method
str = "Safa is a Student."
try :
result = str.index("Safa")
print ("Safa is present in the string.")
except :
print ("Safa is not present in the string.")
Output:
Safa is present in the string.
Method 5: By using the operator.contains() method
Syntax: operator.contains(string,substring)
Example: Checking for the presence of a substring in the string using the operator.contains() method
import operator
str = "Safa is a Student."
if operator.contains(str, "Student"):
print ("Student is present in the string.")
else :
print ("Student is not present in the string.")
Output: Student is present in the string.
References
- Python String