Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python set to check if string is pangram
Next article icon

Python – Check if substring present in string

Last Updated : 05 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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. 

Python
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()
  • Using str.index()
  • Using re.search()

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.

Python
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.

Python
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.

Python
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.


Next Article
Python set to check if string is pangram
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python string-programs
  • python-string
Practice Tags :
  • python

Similar Reads

  • Check if String Contains Substring in Python
    This article will cover how to check if a Python string contains another string or a substring in Python. Given two strings, check whether a substring is in the given string. Input: Substring = "geeks" String="geeks for geeks"Output: yesInput: Substring = "geek" String="geeks for geeks"Output: yesEx
    8 min read
  • How to Substring a String in Python
    A String is a collection of characters arranged in a particular order. A portion of a string is known as a substring. For instance, suppose we have the string "GeeksForGeeks". In that case, some of its substrings are "Geeks", "For", "eeks", and so on. This article will discuss how to substring a str
    4 min read
  • Python set to check if string is pangram
    Given a string, check if the given string is a pangram or not. Examples: Input : The quick brown fox jumps over the lazy dog Output : The string is a pangram Input : geeks for geeks Output : The string is not pangram A normal way would have been to use frequency table and check if all elements were
    2 min read
  • Check for URL in a String - Python
    We are given a string that may contain one or more URLs and our task is to extract them efficiently. This is useful for web scraping, text processing, and data validation. For example: Input: s = "My Profile: https://auth.geeksforgeeks.org/user/Prajjwal%20/articles in the portal of https://www.geeks
    4 min read
  • Check If String is Integer in Python
    In this article, we will explore different possible ways through which we can check if a string is an integer or not. We will explore different methods and see how each method works with a clear understanding. Example: Input2 : "geeksforgeeks"Output2 : geeksforgeeks is not an IntigerExplanation : "g
    4 min read
  • Using Set() in Python Pangram Checking
    Given a string check if it is Pangram or not. A pangram is a sentence containing every letter in the English Alphabet. Lowercase and Uppercase are considered the same. Examples: Input : str = 'The quick brown fox jumps over the lazy dog' Output : Yes // Contains all the characters from ‘a’ to ‘z’ In
    3 min read
  • String Subsequence and Substring in Python
    Subsequence and Substring both are parts of the given String with some differences between them. Both of them are made using the characters in the given String only. The difference between them is that the Substring is the contiguous part of the string and the Subsequence is the non-contiguous part
    5 min read
  • SequenceMatcher in Python for Longest Common Substring
    Given two strings ‘X’ and ‘Y’, print the longest common sub-string. Examples: Input : X = "GeeksforGeeks", Y = "GeeksQuiz" Output : Geeks Input : X = "zxabcdezy", Y = "yzabcdezx" Output : abcdez We have existing solution for this problem please refer Print the longest common substring link. We will
    2 min read
  • Python - Replace all occurrences of a substring in a string
    Replacing all occurrences of a substring in a string means identifying every instance of a specific sequence of characters within a string and substituting it with another sequence of characters. Using replace()replace () method is the most straightforward and efficient way to replace all occurrence
    2 min read
  • Python - Check for float string
    Checking for float string refers to determining whether a given string can represent a floating-point number. A float string is a string that, when parsed, represents a valid float value, such as "3.14", "-2.0", or "0.001". For example: "3.14" is a float string."abc" is not a float string.Using try-
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
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