Find all occurrences of a character in a String


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?

Asked By: Piratenlulatsch



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


[2, 3]
Answered By: Ajax1234

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')]     
Answered By: chepner
def findall(sub, s) :
    pos = -1
    while (pos := s.find(sub,pos+1)) > -1 :
    return hits
Answered By: Stephen Boston
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.