[英]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.