How to replace the repeat word in python (Hangman Game)!
This game now i have solved till the end.But here is 1 more problem that is how can i replace repeat word in string? please help me! Thank you. For example: my customfile inside there is word:"apple" and when hide the word with dashes: "-----" but when i replace in dashes string i can just only replace dash with 1 p:"ap-le" how can i replace dashes with 2p: "apple".My previous post for this program:How do i detect the repeat input in my hangman game (Python)! . Here is my code to replace:
def getGuessedWord(): pos = word.index(guessword.lower()) print(pos) global words words = words[:pos]+ guessword.lower() +words[pos+1:] print(words) return words
My solution to your overall problem of filtering out guessed letters is the following set of functions:
guessed_letters = set() def guess(letter): global guessed_letters guessed_letters.add(letter) def filter_letter(letter): if letter in guessed_letters: return letter else: return '-' def filtered(words): for word in words: output = '' for letter in word: output += filter_letter(letter) yield output
or more compactly:
guessed_letters = set() def guess(letter): global guessed_letters guessed_letters.add(letter) def filter_letter(letter): return letter if letter in guessed_letters else '-' def filtered(words): return [''.join(map(filter_letter, word)) for word in words]
>>> words = "bubbly water".split() >>> guess('a') >>> ' '.join(filtered(words)) '------ -a---' >>> guess('b') >>> ' '.join(filtered(words)) 'b-bb-- -a---