查找字符串中某个字符的所有出现

Find all occurrences of a character in a String

我是 python 的新手,正在尝试构建 Hangman 游戏进行练习。

我正在使用 Python 3.6.1

用户可以输入一个字母,我想告诉他这个字母是否出现在单词中以及它在哪里。

我使用 occurrences = currentWord.count(guess) 得到总出现次数

我有 firstLetterIndex = (currentWord.find(guess)),要获取索引。

现在我有了第一个字母的索引,但是如果这个单词多次出现这个字母怎么办?
我试过 secondLetterIndex = (currentWord.find(guess[firstLetterIndex, currentWordlength])),但没用。
有一个更好的方法吗?也许我找不到内置功能?

执行此操作的一种方法是使用列表理解查找索引:

currentWord = "hello"

guess = "l"

occurrences = currentWord.count(guess)

indices = [i for i, a in enumerate(currentWord) if a == guess]

print indices

输出:

[2, 3]

我会维护第二个布尔值列表,指示哪些字母已正确匹配。

>>> word_to_guess = "thicket"
>>> matched = [False for c in word_to_guess]
>>> for guess in "te":
...   matched = [m or (guess == c) for m, c in zip(matched, word_to_guess)]
...   print(list(zip(matched, word_to_guess)))
...
[(True, 't'), (False, 'h'), (False, 'i'), (False, 'c'), (False, 'k'), (False, 'e'), (True, 't')]
[(True, 't'), (False, 'h'), (False, 'i'), (False, 'c'), (False, 'k'), (True, 'e'), (True, 't')]