How to check if string contains substring in Python
Created
Modified
Using the in Operator
The easiest way to check if a Python string contains a substring is to use the in operator.
str = "Python"
if "th" in str:
print("Found!")
# case-insensitive
if "TH" not in str:
print("Not found!")
Found! Not found!
Using str.Index Method
If the substring is not found, a ValueError exception is thrown, which can be handled with a try-except-else block:
str = "Python"
try:
i = str.index("th")
print(i)
#Found!
except ValueError:
print("Not found!")
Using str.find Method
Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.
str = "Python"
# str.find(sub[, start[, end]])
if str.find("th") != -1:
print("Found!")
Found!
The
find()
method should be used only if you need to know the position of sub. To check if sub is a substring or not, use the in
operator: