简体   繁体   中英

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?

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]

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')]     
def findall(sub, s) :
    pos = -1
    hits=[]
    while (pos := s.find(sub,pos+1)) > -1 :
        hits.append(pos)
    return hits

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM