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 - All occurrences of substring in string
Next article icon

Python | Get the starting index for all occurrences of given substring

Last Updated : 24 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string and a substring, the task is to find out the starting index for all the occurrences of a given substring in a string. Let’s discuss a few methods to solve the given task. 

Method #1: Using Naive Method 

Python3




# Python3 code to demonstrate
# to find all occurrences of substring in
# a string
 
# Initialising string
ini_string = 'xbzefdgstbzefzexezef'
 
# Initialising sub-string
sub_string = 'zef'
 
# Printing initial string and sub-string
print("initial_strings : ", ini_string, "\nsubstring : ", sub_string)
 
res = []
flag = 0
k = 0
 
# Finding all occurrences of substring
# in a string using Naive method
for i in range(0, len(ini_string)):
    k = i
    flag = 0
    for j in range(0, len(sub_string)):
        if ini_string[k] != sub_string[j]:
            flag = 1
        if flag:
            break
        k = k + 1
    if flag == 0:
        res.append(i)
 
 
# printing result(
print("resultant positions", str(res))
 
 
Output:
initial_strings :  xbzefdgstbzefzexezef  substring :  zef resultant positions [2, 10, 17]

Time Complexity: O(n2)
Auxiliary Space O(n)

Method #2: Using list comprehension 

Python3




# Python3 code to demonstrate
# to find all occurrences of substring in
# a string
 
# Initialising string
ini_string = 'xbzefdgstbzefzexezef'
 
# Initialising sub-string
sub_string = 'zef'
 
# Printing initial string and sub-string
print("initial_strings : ", ini_string, "\nsubstring : ", sub_string)
 
res = []
# Finding all occurrences of substring
# in a string using list comprehension
res = [i for i in range(len(ini_string))
       if ini_string.startswith(sub_string, i)]
 
# printing result(
print("resultant positions", str(res))
 
 
Output:
initial_strings :  xbzefdgstbzefzexezef  substring :  zef resultant positions [2, 10, 17]

Time Complexity: O(n2)
Auxiliary Space O(n)

  Method #3: Using regex 

Python3




# Python3 code to demonstrate
# to find all occurrences of substring in
# a string
import re
 
# Initialising string
ini_string = 'xbzefdgstbzefzexezef'
 
# Initialising sub-string
sub_string = 'zef'
 
# Printing initial string and sub-string
print("initial_strings : ", ini_string, "\nsubstring : ", sub_string)
 
res = []
# Finding all occurrences of substring
# in a string using re.finditer
res = [m.start() for m in re.finditer(sub_string, ini_string)]
 
# printing result(
print("resultant positions", str(res))
 
 
Output:
initial_strings :  xbzefdgstbzefzexezef  substring :  zef resultant positions [2, 10, 17]

Time Complexity: O(n2)
Auxiliary Space: O(n)

Method #4 : Using find() and replace() methods

Python3




# Python3 code to demonstrate
# to find all occurrences of substring in
# a string
 
# Initialising string
ini_string = 'xbzefdgstbzefzexezef'
 
# Initialising sub-string
sub_string = 'zef'
 
# Printing initial string and sub-string
print("initial_strings : ", ini_string, "\nsubstring : ", sub_string)
 
res = []
while(ini_string.find(sub_string) != -1):
    res.append(ini_string.find(sub_string))
    ini_string = ini_string.replace(sub_string, "*"*len(sub_string), 1)
 
# printing result(
print("resultant positions", str(res))
 
 
Output
initial_strings :  xbzefdgstbzefzexezef  substring :  zef resultant positions [2, 10, 17]

Time Complexity: O(n2)
Auxiliary Space: O(n)

Using str.index() in a loop:

Approach:

In this example, the string variable contains the string we want to search in, and the substring variable contains the substring we want to find. We pass these variables as arguments to the get_substring_indices() function and store the result in the indices variable. Finally, we print the indices variable to see the starting index for all occurrences of the given substring.

Python3




def get_substring_indices(string, substring):
    indices = []
    try:
        index = string.index(substring)
        while index != -1:
            indices.append(index)
            index = string.index(substring, index + 1)
    except ValueError:
        pass
    return indices
 
string = "hello world, world is beautiful"
substring = "world"
indices = get_substring_indices(string, substring)
print(indices)  # Output: [6, 18]
 
 
Output
[6, 13]

Time Complexity: O(n*m), where n is the length of the string and m is the length of the substring
Auxiliary Space: O(1)



Next Article
Python - All occurrences of substring in string
author
garg_ak0109
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Python | Get the string after occurrence of given substring
    The problem involves getting the string that is occurring after the substring has been found. Let's discuss certain ways in which this task can be performed using Python. Using partition()To extract the portion of a string that occurs after a specific substring partition() method is an efficient and
    3 min read
  • Python - All occurrences of substring in string
    A substring is a contiguous occurrence of characters within a string. Identifying all instances of a substring is important for verifying various tasks. In this article, we will check all occurrences of a substring in String. Using re.finditer()re.finditer() returns an iterator yielding match object
    3 min read
  • Python - All occurrences of Substring from the list of strings
    Given a list of strings and a list of substring. The task is to extract all the occurrences of a substring from the list of strings. Examples: Input : test_list = ["gfg is best", "gfg is good for CS", "gfg is recommended for CS"] subs_list = ["gfg", "CS"] Output : ['gfg is good for CS', 'gfg is reco
    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
  • Get Second Occurrence of Substring in Python String
    We are given a string and a substring, and our task is to find the index of the second occurrence of that substring within the string. This means we need to identify not just if the substring exists, but where it appears for the second time. For example, if we have a string like "hello world, hello
    2 min read
  • Python program to find the occurrence of substring in the string
    Given a list of words, extract all the indices where those words occur in the string. Input : test_str = 'geeksforgeeks is best for geeks and cs', test_list = ["best", "geeks"] Output : [2, 4] Explanation : best and geeks occur at 2nd and 4th index respectively. Input : test_str = 'geeksforgeeks is
    4 min read
  • Python - Get all substrings of given string
    A substring is any contiguous sequence of characters within the string. We'll discuss various methods to extract this substring from a given string by using a simple approach. Using List Comprehension :List comprehension offers a concise way to create lists by applying an expression to each element
    3 min read
  • Count Occurance of Substring in a List of Strings - Python
    To count the occurrences of a particular substring in a list of strings in Python, we can use several methods. In this article, we are going to explore different methods to count the existence of a particular substring in a given list. Using sum() and Generator ExpressionThis method uses a generator
    3 min read
  • Python | Frequency of substring in given string
    Finding a substring in a string has been dealt with in many ways. But sometimes, we are just interested to know how many times a particular substring occurs in a string. Let's discuss certain ways in which this task is performed. Method #1: Using count() This is a quite straightforward method in whi
    6 min read
  • Print Substrings that are Prefix of the Given String - Python
    The task of printing the substrings that are prefixes of a given string involves generating all the possible substrings that start from the first character of the string and end at any subsequent position.For example, if the given string is s = "hello", the prefixes of the string would include "h",
    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