Python - Check if substring present in string
The task is to check if a specific substring is present within a larger string. Python offers several methods to perform this check, from simple string methods to more advanced techniques. In this article, we'll explore these different methods to efficiently perform this check.
Using in operator
This operator is the fastest method to check for a substring, the power of in operator in Python is very well known and is used in many operations across the entire language.
s= "GeeksforGeeks"
# Check if "for" exists in `s`
if "for" in s:
print(True)
else:
print(False)
Output
True
Let's understand different methods to check if substring present in string.
Table of Content
Using str.find()
find() method searches for a substring in a string and returns its starting index if found, or -1 if not found. It's useful for checking the presence of a specific word or phrase in a string.
s= "GeeksforGeeks"
# to check for substring
res = s.find("for")
if res >= 0:
print(True)
else:
print(False)
Output
True
Explanation:
- s.find():This looks "for" word in `s` and gives its position. If not found, it returns -1.
Using str.index()
str.index() method helps us to find the position of a specific word or character in a string. If the word isn't found, it throws an error, unlike find() which just returns -1. It's useful when we want to catch the error if the word is missing.
s= "GeeksforGeeks"
try:
# to check for substring
res = s.index("for")
print(True)
except ValueError:
print(False)
Output
True
Explanation
- s.index("for"): This searches for the substring "for" in `s`.
- except ValueError: This catches the error if the substring is not found, and prints False.
Using re.search()
re.search()
finds a pattern in a string using regular expressions. It's slower for simple searches due to extra processing overhead.
import re
s= "GeeksforGeeks"
if re.search("for", s):
print(True)
else:
print(False)
Output
True
Explanation:
- if re.search("for", s): This checks if the substring was found. If found, it returns a match object, which evaluates to True.