首页 > 解决方案 > 如何获取字符串中单词的索引

问题描述

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

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)

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

标签: pythonre

解决方案


修复:

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 行,我反转了(字符串,单词)。请检查文档以了解正确用法。


推荐阅读