[英]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]))
,但这不起作用。
有一个更好的方法吗? 也许我找不到 function 中的构建?
一种方法是使用列表理解来找到索引:
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')]
def findall(sub, s) :
pos = -1
hits=[]
while (pos := s.find(sub,pos+1)) > -1 :
hits.append(pos)
return hits
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.