"""
Find all starting indices of a word inside a larger text.
This function uses str.find in a loop. The method is efficient
and implemented in optimized C code inside Python's runtime.
"""
def find_all_occurrences(text: str, word: str) -> list[int]:
indices = []
# Searching for an empty word is meaningless
if word == "":
return indices
index = text.find(word) # First occurrence
while index != -1:
indices.append(index) # Store the index
"""
Search again starting one character after the previous match.
This allows detection of overlapping matches.
"""
index = text.find(word, index + 1)
return indices
def main():
text = "the quick brown fox jumps over the lazy dog. the fox is clever."
word = "the"
print("Text:", text)
print(f'Word: "{word}"\n')
print("Occurrences at indices:")
for idx in find_all_occurrences(text, word):
print(idx)
if __name__ == "__main__":
main()
"""
run:
Text: the quick brown fox jumps over the lazy dog. the fox is clever.
Word: "the"
Occurrences at indices:
0
31
45
"""