How do i find the position of MORE THAN ONE substring in a string (Python 3.4.3 shell)

醉酒当歌 提交于 2019-12-02 04:08:17
sentence = input("Please input a sentence: ")
word = input("Please input a word: ")
sentence = sentence.lower()
word = word.lower()
wordlist = sentence.split(' ')
print ("Your word '%s' is in these positions:" % word)
for position,w in enumerate(wordlist):
    if w == word:
        print("%d" % position + 1)

Use enumerate:

[i for i, w in enumerate(s.split()) if w == 'test']

Example:

s = 'test test something something test'

Output:

[0, 1, 4]

But i guess it's not what you are looking for, if you need starting indexes for words in a string i would recommend to use re.finditer:

import re

[w.start() for w in re.finditer('test', s)]

And the output for the same s would be:

[0, 5, 30]

Another solution that does not split on space.

def multipos(string, pattern):

    res = []
    count = 0
    while True:
        pos = string.find(pattern)
        if pos == -1:
            break
        else:
            res += [pos+count]
            count += pos+1
            string = string[pos+1:]

    return res


test = "aaaa 123 bbbb 123 cccc 123"
res = multipos("aaaa 123 bbbb 123 cccc 123", "123")
print res
for a in res:
    print test[a:a+3]

And the script output :

% python multipos.py
[5, 14, 23]
123
123
123
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!