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

Python Methods and Functions | Regular Expressions | String Variables

Method # 1: Using the naive method

# Python3 demo code
# find all occurrences of a substring in
# string

 
# Initializing string

ini_string = 'xbzefdgstbzefzexezef'

  
# Substring initialization

sub_string = 'zef'

  
# Print start line and substring

print (  "initial_strings:" , ini_string, "substring:" , sub_string)

 

res = []

flag = 0

k = 0

 
# Find all occurrences of a substring
# on a line using the 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)

 

 
# print result (

print ( "resultant positions" , str (res))

< / td>

Exit:

 initial_strings: xbzefdgstbzefzexezef substring: zef resultant positions [2, 10 , 17] 

& amp; Nsbp; 
Method # 2: Using List Comprehension

# Python3 demo code
# find all occurrences of a substring in
# string

  
# Initializing string

ini_string = ' xbzefdgstbzefzexezef'

 
# Substring initialization

sub_string = ' zef'

 
# Print start line and substring

print ( " initial_strings: " , ini_string, " substring: " , sub_string)

 

res = []

# Find all occurrences of a substring
# per line using a list comprehension

res = [i for i in range ( len (ini_string)) 

if ini_string.startswith (sub_string, i)]

  
# print result (

print ( " resultant positions " , str (res))

Exit :

 initial_strings: xbzefdgstbzefzexezef substring : zef resultant positions [2, 10, 17] 

Method # 3: Using regular expressions

# Python3 demo code
# find all occurrences of a substring in
# string

import re

 
# Initializing string

ini_string = ' xbzefdgstbzefzexezef'

 
# Substring initialization

sub_string = ' zef'

 
# Print start line and substring

print ( "initial_strings:" , ini_string, "substring:" , sub_string)

 

res = []

# Find all occurrences of a substring
# in a line using re.finditer

res = [m.start () for m in re.finditer (sub_string, ini_string)]

 
# print result (

print ( " resultant positions " , str (res))

Output:

 initial_strings: xbzefdgstbzefzexezef substring: zef resultant positions [2, 10, 17] 




Get Solution for free from DataCamp guru