The task is to check if a specificsubstring is present within a larger string.Pythonoffers 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
Thisoperator 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.
Pythons="GeeksforGeeks"# Check if "for" exists in `s`if"for"ins:print(True)else:print(False)
Let's understand different methods to check if substring present in string.
Using str.find()
find() method searches for a substring in a stringand 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.
Pythons="GeeksforGeeks"# to check for substringres=s.find("for")ifres>=0:print(True)else:print(False)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.
Pythons="GeeksforGeeks"try:# to check for substringres=s.index("for")print(True)exceptValueError:print(False)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 usingregular expressions. It's slower for simple searches due to extra processing overhead.
Pythonimportres="GeeksforGeeks"ifre.search("for",s):print(True)else:print(False)Explanation:
- if re.search("for", s):This checks if the substring was found. If found, it returns a match object, which evaluates to True.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice