×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

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

By Sapna Deraje Radhakrishna Last updated : December 15, 2024

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

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

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.

Example

# 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()

The following code demonstrates how to find all occurrences of a word in a sentence using the str.find() method.

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

This code uses list comprehension to find and print all starting indices of a word in a sentence.

Example

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.