如何获取字符串中单词的索引

How to get index of a word in a string

我正在尝试 运行 以下内容:-

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)

结果我只得到一个空列表。但是 运行ning 没有函数的代码给出了关键字所有索引的结果。任何帮助将不胜感激!!!

已修复:

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)

第5行,我反转了(string, word)。请检查文档以正确使用。

re.finditer(pattern, string, flags=0) 将第一个参数作为 patternsecond 作为 string:

def findword(string, word):
    import re
    strings = string.split()
    if word in strings:
        matches = re.finditer(word, string) # see the change here
        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)

输出:

[9, 26, 30]