How can I find all indices where a substring appears in a string?


#1

Question

In the context of this exercise, how can I find all indices where a substring appears in a string?

Answer

In this exercise, we were introduced to the .find() method, but it will only return the first index where the substring appears in a string.

To obtain all the indices where a substring appears, you can use a loop to iterate over the entire string, and keep track of each match’s starting index.

target = "abc"
string = "abcdababcd"

indices = []
for i in range(len(string)):
  if string[i:i+len(target)] == target:
    indices.append(i)

print(indices) # [0, 6]