问题
I'm really new to python and trying to build a Hangman Game for practice.
I'm using Python 3.6.1
The User can enter a letter and I want to tell him if there is any occurrence of that letter in the word and where it is.
I get the total number of occurrences by using occurrences = currentWord.count(guess)
I have firstLetterIndex = (currentWord.find(guess))
, to get the index.
Now I have the index of the first Letter, but what if the word has this letter multiple times?
I tried secondLetterIndex = (currentWord.find(guess[firstLetterIndex, currentWordlength]))
, but that doesn't work.
Is there a better way to do this? Maybe a build in function i can't find?
回答1:
One way to do this is to find the indices using list comprehension:
currentWord = "hello"
guess = "l"
occurrences = currentWord.count(guess)
indices = [i for i, a in enumerate(currentWord) if a == guess]
print indices
output:
[2, 3]
回答2:
I would maintain a second list of Booleans indicating which letters have been correctly matched.
>>> 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')]
来源:https://stackoverflow.com/questions/44307988/find-all-occurrences-of-a-character-in-a-string