Finding indexes of substrings

Question:

I am trying to code a program to find the index of multiple substrings of a string but I am stuck! See the examples bellow:

Find : 'yes'
Input = 'adnyesdapodyesndudndnyesae'
Output = [3,11,21]
Find : 'b'
Input = 'bbbbbbb'
Output = [0,1,2,3,4,5,6]
Asked By: John Drew

||

Answers:

You need to loop through the range of numbers based on the string lengths then take the slice of input string from i to n number of characters where n is the length of the string to find, then compare for equality. You can implement using List-Comprehension:

>>> n = len(Find)
>>> [i for i in range(len(Input)-n) if Input[i:i+n]==Find]
# Output:
[3, 11, 21]
Answered By: ThePyGuy
F = 'yes'
I = 'adnyesdapodyesndudndnyesae'

[n for n in range(len(I)) if I.find(F, n) == n]

Here we are using the find() method of string to get the index

[3, 11, 21]

F = 'b'
I = 'bbbbbbb'

[n for n in range(len(I)) if I.find(F, n) == n]
[0, 1, 2, 3, 4, 5, 6]

#2 A simple while loop solution:

def findall(f, s):
    l = []
    i = -1
    while True:
        i = s.find(f, i+1)
        if i == -1:
            return l
        l.append(s.find(f, i))

print(findall(F, I))
[0, 1, 2, 3, 4, 5, 6]
Answered By: God Is One

You should use Pythons built-in module re to do this easily:

import re

def find_all_occurances(string, sub_string):
    return [match.start() for match in re.finditer(sub_string, string)]

If you want to include overlapping matches with re, you can do:

import re

def find_all_occurances(string, sub_string):
    return [match.start() for match in re.finditer(f"(?={sub_string})", string)]

Otherwise, this is easily done using plain Python:

def find_all_occurances(string, sub_string):
    occurances = []

    start = 0

    while (start := string.find(sub_string, start)) != -1:
        occurances.append(start)
        start += len(sub_string)  # use start += 1 to find overlapping matches

    return occurances
Answered By: chrille0313
str1 = "adnyesdapodyesndudndnyesae" #The String
substr = "yes" #The Substring
res = [i for i in range(len(str1)) if str1.startswith(substr, i)]
print(str(res))

The third line basically runs a list comprehension method wherein using a for loop you check for occurences of a substring in the string.

Answered By: The Myth
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.