Python | All occurrences of a substring in a string

Method # 1: Using Comprehension List + startswith()
This task can be accomplished using two functions. The start with function mainly performs the task of getting the starting indices of the substring, and the list comprehension is used to iterate over the entire target string.

# Python3 demo code
# All occurrences of a substring in a string
# Using comprehension list + startwith ()

 
# initialization string

test_str = "Python.Engineering is best for Geeks"

 
# substring initialization

test_sub = "Geeks"

  # print original line

print ( "The original string is:" + test_str)

 
# print substring

print ( " The substring to find: " + test_sub)

 
# use comprehension list + startwith ()
# All occurrences of the substring in the string

res = [i for i in range ( len (test_str)) if test_str.startswith (test_sub, i)]

 
# print result

print ( "The start indices of the substrings are:" + str ( res))

Output:

 The original string is: Python.Engineering is best for Geeks The substring to find: Geeks The start indices of the substrings are: [0, 8, 26] 

Method # 2: Using re.finditer ()
The finditer function of the regex library can help us perform the task of finding occurrences of a substring in the target string, and the start function can return the resulting index of each them.

# Python3 code to demonstrate how it works
# All occurrences of a substring in the string
# Using re.finditer ()

import re

  
# initialization string

test_str = "Python.Engineering is best for Geeks"

 
# substring initialization

test_sub = " Geeks "

  
# print the original line

print  ( "The original string is:" + test_str)

 
# print substring

print ( "The substring to find:" + test_sub)

  
# using re.finditer ()
# All occurrences of a substring in a string

res = [i.start () for i in re.finditer (test_sub, test_str)]

 
# print result < / p>

print ( "The start indices of the substrings are:" + str (res))

Output:

 The original string is: Python.Engineering is best for Geeks The substring to find: Geeks The start indices of the substrings are: [0, 8, 26]