如何找到一个字符串中多个子串的位置 (Python 3.4.3 shell)

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

以下代码显示 "word" 在字符串中出现一次的位置。我如何更改我的代码,以便如果 "word" 在字符串中出现不止一次,它会打印所有位置?

string = input("Please input a sentence: ")
word = input("Please input a word: ")
string.lower()
word.lower()
list1 = string.split(' ')
position = list1.index(word)
location = (position+1)
print("You're word, {0}, is in position {1}".format (word, location))

使用enumerate:

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

示例:

s = 'test test something something test'

输出:

[0, 1, 4]

但我想这不是你要找的,如果你需要字符串中单词的起始索引,我建议使用 re.finditer:

import re

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

同一个 s 的输出将是:

[0, 5, 30]
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)

另一种在 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]

脚本输出:

% python multipos.py
[5, 14, 23]
123
123
123