Home » Python

Find all the indexes of all the occurrences of a word in a string in Python

Here, we are going to learn how to find all the indexes of all the occurrences of a word in a string in Python?
Submitted by Sapna Deraje Radhakrishna, on October 13, 2019

To retrieve the index of all the occurrences of a word in the string (say a statement), Python, like most of the programming languages supports the regular expression module as a built-in module. Or if we don't want the overhead of using the regular expressions, we could also use the str.index() in an iteration to get the index and also using the comprehension.

1) Using the regular expression module

Example:

The below example, explains the usage of the regex module's (re) method finditer() which takes the 'word' or substring to be searched for and the sentence in which the 'word' shall be searched, as the argument.

The output of the below example is the start index and end index of the word 'to' in the sentence.

Code:

# importing the module
import re

# sentence and word to be found
sentence = "This is a sample sentence to search for include help to search all occurrences"
word = "to"

# logic
for match in re.finditer(word, sentence):
    print("match found from {} to {}".format(match.start(), match.end()))

Output

match found from 26 to 28
match found from 53 to 55

2) Using the str.index()

Python:

def using_str_index (word, sentence):
    index = 0;
    while index < len(sentence):
        index = sentence.find(word, index)
        if index == -1:
            break
        print('{} found at {}'.format(word, index))
        index += len(word)

if __name__ == '__main__':    
    sentence = "This is a sample sentence to search for include help to search all occurrences"
    word = "to"
    using_str_index(word, sentence)

Output

to found at 26
to found at 53

3) Using comprehension

Code:

def using_comprehension(word, sentence):
    print([n for n in range(len(sentence)) if sentence.find(word, n) == n])

if __name__== "__main__":
    sentence = "This is a sample sentence to search for include help to search all occurrences"
    word = "to"
    using_comprehension(word, sentence)

Output

[26, 53]


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.