mercredi 9 décembre 2020

Is there a way to replace letters of a word that were converted to underscores with letters a user inserted, if letters inserted = letters from word?

this question is based on a game I am currently creating just to get into python. Say I have a secret word. This secret word is selected from a simple list containing random words by using:

random_word_generator = open("random_words.txt", "r")
random_words = list(random_word_generator)
secret_word = random.choice(random_words)

I converted the word into underscores by using

underscore = ("_ " * len(secret_word))

and then displayed it:

print("My secret word is " + str(len(secret_word)) + " letters long: " + underscore)

what I now would like to do is the following:

when a user inputs a letter that is within the secret word, I want the underscore representing the letter from that word to be replaced by the letter the user inserted.

e.g.

water


user input:

"a"

since a is within "water" --> _ a _ _ _

and so on...

also, if the user guessed a letter that occurs multiple times in a word, I would like all the underscores representing that letter to be replaced simultaneously...

e.g.

"elephant"


user input: "e" --> e _ e _ _ _ _ _

I tried a .replace method, but that method probably is too limited in it's capabilities to reflect the desired output

Any hint is appreciated!




Aucun commentaire:

Enregistrer un commentaire