Search code examples
pythonpython-re

How to get index of a word in a string


I am trying to run the below: -

def findword(string, word):
    import re
    strings=string.split()
    if word in strings:
        matches = re.finditer(string, word)
        matches_positions = [match.start() for match in matches]
        print(matches_positions)
    else:
        print("Word not found")

string=" how are you doing how do you you"
word= "you"
findword(string, word)

I'm only getting an empty list as result. But running the code without function gives the result of all index of the keyword. Any help would be appreciated !!!


Solution

  • Fixed it:

    def findword(string, word):
        import re
        strings=string.split()
        if word in strings:
            matches = re.finditer(word ,string) #reversed (string, word), check documentation for correct usage
            matches_positions = [match.start() for match in matches]
            print(matches_positions)
        else:
            print("Word not found")
    
    string=" how are you doing how do you you"
    word= "you"
    findword(string, word)
    

    On line 5, I reversed (string, word). Please check the documentation for correct usage.