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:
Find Length of String in Python
Next article icon

Find the Index of a Substring in Python

Last Updated : 19 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Finding the position of a substring within a string is a common task in Python. In this article, we will explore some simple and commonly used methods to find the index of a substring in Python.

Using str.find()

The find() method searches for the first occurrence of the specified substring and returns its starting index. If the substring is not found, it returns -1.

python-substring-indexof
Using find() to check the index of a substring

Example:

Python
s = "GeeksforGeeks"  # Define the substring we want to find s1 = "eeks"  # Use the find() method to locate the starting index of the substring 's1' in the string 's' index = s.find(s1) #Print either satarting position of 's1' or -1 if not found print(index) 

Output
1 

Table of Content

  • Using str.index()
  • Using split() Function
  • Using re.search()

Using str.index()

The index() method is similar to find() but raises a ValueError if the substring is not found. This method requires error handling if the substring is not present.

Python
s = "GeeksforGeeks"  # Define the substring we want to find s1 = "or"  try:   #index() returns the starting position of 's1' in 's'     index = s.index(s1)     print(f"The substring '{s1}' is found at index {index}.") except ValueError:   ## If the substring is not found, the index() method raises a ValueError     print(f"The substring '{s1}' is not present in the text.") 

Output
The substring 'or' is found at index 6. 

Using str.split()

This approach works well for word-based matches. Splitting the string and finding the substring's index in the resulting list can be useful for finding whole words.

Python
s = "Geeks for Geeks"  # Define the substring we want to find s1 = "for"  parts = s.split(s1)  # Check if the substring is in the string if len(parts) > 1:     # Calculate the starting index of the substring     index = len(parts[0])      print(f"The substring '{s1}' is found at index {index}.") else:     print(f"The substring '{s1}' is not present in the text.") 

Output
The substring 'for' is found at index 6. 

Using re.search()

The re.search() in Python's re module can be used to locate the first occurrence of a pattern in a string. While re.search() itself doesn’t directly return the starting or ending index of the match with this you can extract this information using the Match object's start() and end() methods.

Python
import re  s = "hello world" s1 = "ello"  # Use the re.search() function to search for the substring in the main string match = re.search(s1, s) if match:   # If a match exists, print the starting index of the substring     print(f"The substring '{s1}' is found at index {match.start()}") else:   # If no match is found, print that the substring is not present     print(f"The substring '{s1}' is not present in the text") 

Output
The substring 'ello' is found at index 1 

Next Article
Find Length of String in Python

K

khanaayuxyc
Improve
Article Tags :
  • Python
  • Python Programs
  • substring
Practice Tags :
  • python

Similar Reads

  • How to Find Index of a Substring in Python
    In Python, sometimes we need to know where a certain substring appears in a string. To do this, we can find the index (or position) of that substring. The index tells us where the substring is located. Let’s look at some simple ways to find the index of a substring in a string. Using find() methodTh
    2 min read
  • How to Get Index of a Substring in Python?
    To get index of a substring within a Python string can be done using several methods such as str.find(), str.index(), and even regular expressions. Each approach has its own use case depending on the requirements. Let’s explore how to efficiently get the index of a substring. The simplest way to get
    2 min read
  • Find Length of String in Python
    In this article, we will learn how to find length of a string. Using the built-in function len() is the most efficient method. It returns the number of items in a container. [GFGTABS] Python a = "geeks" print(len(a)) [/GFGTABS]Output5 Using for loop and 'in' operatorA string can be iterate
    2 min read
  • Python program to find String in a List
    Searching for a string in a list is a common operation in Python. Whether we're dealing with small lists or large datasets, knowing how to efficiently search for strings can save both time and effort. In this article, we’ll explore several methods to find a string in a list, starting from the most e
    3 min read
  • Python - Find Index containing String in List
    In this article, we will explore how to find the index of a string in a list in Python. It involves identifying the position where a specific string appears within the list. Using index()index() method in Python is used to find the position of a specific string in a list. It returns the index of the
    3 min read
  • Python - Find the sum of Length of Strings at given indices
    Given the String list, write a Python program to compute sum of lengths of custom indices of list. Examples: Input : test_list = ["gfg", "is", "best", "for", "geeks"], idx_list = [0, 1, 4] Output : 10 Explanation : 3 + 2 + 5 = 10. (Sizes of strings at idx.) Input : test_list = ["gfg", "is", "best",
    4 min read
  • Python | Find last occurrence of substring
    Sometimes, while working with strings, we need to find if a substring exists in the string. This problem is quite common and its solution has been discussed many times before. The variation of getting the last occurrence of the string is discussed here. Let's discuss certain ways in which we can fin
    8 min read
  • Python | Get first index values in tuple of strings
    Yet another peculiar problem which might not be common, but can occur in python programming while playing with tuples. Since tuples are immutable, they are difficult to manipulate and hence knowledge of possible variation solutions always helps. This articles solves problem of extracting only the fi
    5 min read
  • Python | Ways to find nth occurrence of substring in a string
    Given a string and a substring, write a Python program to find the nth occurrence of the string. Let's discuss a few methods to solve the given task. Get Nth occurrence of a substring in a String using regex Here, we find the index of the 'ab' character in the 4th position using the regex re.findite
    4 min read
  • Finding Strings with Given Substring in List - Python
    The task of finding strings with a given substring in a list in Python involves checking whether a specific substring exists within any of the strings in a list. The goal is to efficiently determine if the desired substring is present in any of the elements of the list. For example, given a list a =
    3 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