在字符串中查找单词的位置
这个问题在这里已经有了答案:
要在输入字符串中获得搜索字符串jake
的“序号”位置,请使用以下方法:
mystr = "there not what is jake can do for you ask what you play do for spare jake"
search_str = 'jake'
result = [i+1 for i,w in enumerate(mystr.split()) if w.lower() == search_str]
print(result)
输出:
[5, 17]
enumerate(mystr.split())
- 获取枚举对象(项目对与它们的位置/索引)
w.lower() == search_str
- 如果一个单词等于搜索字符串
试试这种方式:
mystr = "there not what is jake can do for you ask what you play do for spare jake"
result = [index+1 for index,word in enumerate(mystr.split()) if word=='jake']
result
输出:
[5, 17]
链接地址: http://www.djcxy.com/p/28123.html
上一篇: Finding the position of words in a string
下一篇: Python: lists .remove(item) but not .find(item) or similar?