python - 如何获取字符串中单词的索引
问题描述
我正在尝试运行以下内容: -
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)
结果我只得到一个空列表。但是在没有函数的情况下运行代码会给出关键字所有索引的结果。任何帮助,将不胜感激 !!!
解决方案
修复:
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 行,我反转了(字符串,单词)。请检查文档以了解正确用法。
推荐阅读
- android - 我是否需要在自定义视图中清除/清空我的视图绑定字段?
- javascript - 循环遍历数组,计算平均值,并在对象中返回结果
- node.js - 如何在节点中使用 ssl 制作服务器?
- c# - Xamarin - 如何使用 MVVM 和数据库绑定标签
- powerbi - 如何从共享点站点将多列转换为文本?
- reactjs - 当我触发 onClick 时 useState 不切换类
- html - 设置一个 web 服务器,将 index.html 上传到 ftp 服务器
- python - 在 matplotlib 中为注释框指定固定宽度
- sql - Redshift:使用另一个带有 JOIN 的表与没有 JOIN 的表更新一个表
- r - 如何在列表中查找重复项并删除其中一个