Last Updated On By Anmol Lohana
A Python string always contains substrings that are the character sequence. Sometimes a programmer needs to check whether a Python string contains a Python substring or not that is required.
This section is going to give you an overview of this topic. We will check Python string contains the required substring or not. There are some methods to find Python string contains that we will discuss below.
Table of Contents
The Python find() method uses to check whether the string contains target string or not. It will return the index at the start of the substring if the string contains a specific substring, and it will return -1 if the string does not contain a particular substring.
string.find(substring)
This example will find the starting index of the particular substring.
str="Hello! Welcome to CodeLeaks."
sub1="Hello"
sub2="CodeLeaks"
print(str.find(sub1))
print(str.find(sub2))
The Python ‘in’ operator is used to check the existence of a particular substring inside a string object. This operator will return boolean values. If the string contains a particular substring, it will return true, and if the string does not contain a particular substring in the string, it will return false.
substring in string
This example will find the existence of a particular substring.
str="Hello! Welcome to CodeLeaks."
sub1="Hello"
sub2="Python"
print(sub1 in str)
print(sub2 in str)
The Python count() Method will count the occurrence of a particular substring inside of the original string. It will return the number of occurrences, but if the substring does not exist, it will return 0.
string.count(substring)
str="Hello! Welcome to CodeLeaks."
sub1="Hello"
sub2="Python"
sub3="CodeLeaks"
print(str.count(sub1))
print(str.count(sub2))
print(str.count(sub3))
The Python index() Method will check the presence of a particular substring in the string. It will return an exception error if the value is not present in the string. Else, it will return what we want.
string.index(substring)
This example is going to check the presence of a particular substring.
str="Hello! Welcome to CodeLeaks."
try :
result = str.index("Hello")
print ("Hello is present in the string.")
except :
print ("Hello is not present in the string.")
It will check the presence of a particular substring in the string.
operator.contains(string, substring)
This example is going to check the existence of a particular substring.
import operator
str="Hello! Welcome to CodeLeaks."
if operator.contains(str, "Hello"):
print ("Hello is present in the string.")
else :
print ("Hello is not present in the string.")
In conclusion, we had an overview of Python string contains. We saw five different methods of Python string contains with coding examples. We used these methods to know the presence of a particular substring, the number of occurrences of the specific substring, particular substring existence, etc.