Find Word Occurrences in a String

Tags: re

Write a Python program that uses the re module to find all occurrences of a word in a string. The function find_occurrences(s, word) should return a list of indices at which word starts in the string s.

Example 1:

Input: find_occurrences("hello world, hello again", "hello")
Output: [0, 13]

Example 2:

Input: find_occurrences("one fish, two fish, red fish, blue fish", "fish")
Output: [4, 14, 24, 35]

Use the re.finditer() function from the re module.

import re

def find_occurrences(s, word):
    return [match.start() for match in re.finditer(word, s)]

# Test the function
print(find_occurrences("hello world, hello again", "hello"))
print(find_occurrences("one fish, two fish, red fish, blue fish", "fish"))

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!