19
loading...
This website collects cookies to deliver better user experience
contains
function. Python also supports the __contains__
method, however, it also supports a few faster and more readable methods to check if a python string contains a substring.in
is mainly used when the user only wants to check if it python string contains the substring and also because it is more readable. However, in case you are looking to return the index of the substring, the next solution is the goto.'substring` in string
not in
is the same. if "Hire" in "Hire the top freelancers":
print("Exists")
else:
print("Dose not exist")
#Output - Exists
in
operator is case sensitive, and the above code would've returned a false if the substring was "hire"
and hence is a good practice to use it with the .lower()
method. This method converts the string to lower case. As strings are immutable, this would not affect the original string.if "hire" in "Hire the top freelancers".lower():
print("Exists")
else:
print("Dose not exist")
#Output - Exists
find()
and Index()
methods. These methods stand out from in
as they return the index of the substring. However, they come with their cons we discuss them more in detail.string.index()
method returns the starting index of the substring passed as a parameter. In this way, it could be used to check if a python string contains a substring. However, a major con is that in case the substring does not exist this method returns a ValueError
and hence it needs to be placed inside a Try Except
.index()
:string.index(value, start, stop)
string
is the python string and value
in the substring. The syntax also contains two optional parameters start
and stop
these are used in case you are looking for a substring within a particular index. index()
:try:
"Hire the top freelancers".index("Hire")
except ValueError:
print("Dose not exist")
else:
print(sting.index(sti))
#Output = 0
index()
is case sensitive and using the .lower() is recommended.try:
"Hire the top freelancers".lower().index("hire")
except ValueError:
print("Dose not exist")
else:
print(sting.index(sti))
#Output = 0
string.find()
is another method that can be used to check if the python string contains the substring. Similar to index()
, find()
also returns the starting index of the substring. But unlike the index()
method it does not return a ValueError
in case the substring does not exist but rather returns -1
which is the index of the left-most string. find()
:string.find(value, start, end)
find()
are the same as index()
find()
:if "Hire the top freelancers".find("Hire") != -1:
print("Hire the top freelancers".find("Hire"))
else:
print("Dose not exist")
find()
is also case sensitive the following code can be used.if "Hire the top freelancers".lower().find("hire") != -1:
print("Hire the top freelancers".find("Hire"))
else:
print("Dose not exist")
.lower()
methods as all the methods are case sensitive.index()
method to ensure it is placed inside an try and except condition.