Movatterモバイル変換


[0]ホーム

URL:


Open In App

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. 

Python
s="GeeksforGeeks"# Check if "for" exists in `s`if"for"ins:print(True)else:print(False)

Output
True

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.

Python
s="GeeksforGeeks"# to check for substringres=s.find("for")ifres>=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.

Python
s="GeeksforGeeks"try:# to check for substringres=s.index("for")print(True)exceptValueError: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 usingregular expressions. It's slower for simple searches due to extra processing overhead.

Python
importres="GeeksforGeeks"ifre.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.

Improve

Explore

Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp