Find all occurrences of a character in a String

空扰寡人 提交于 2020-01-21 09:14:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!