Finding the position of words in a string
This question already has an answer here:
To get the "ordinal" positions of search string jake
in the input string use the following approach:
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)
The output:
[5, 17]
enumerate(mystr.split())
- to get enumerated object (pairs of items with their positions/indices)
w.lower() == search_str
- if a word is equal to search string
Try this way:
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
Output:
[5, 17]
链接地址: http://www.djcxy.com/p/28124.html
上一篇: “如果不在”在Python中获取索引
下一篇: 在字符串中查找单词的位置