How to replace a string with the user input in its designated spot – hangman

Question:

displayed_word = ["-"*length]

#how do you write the guess in the designated spot in hangman?? and to replace the "-" ]
        designated_spot = s.find(guess)
        how_many = s.count(guess)
        print(f"the word had {how_many} of your guess in it")
        print(designated_spot)
        newletter = s.replace(guess, designated_spot)
        print(newletter)

I know a did a lot wrong here but i dont know what to do and how to write it.

I tried to do replace but i realised you couldnt use an integer and the integer is designated_spot and fhsdjkfsh

also s is the random.choice of my list

So I am trying to replace a user input aka "guess" in the designated spot where the guess fits in the random choice that python has generated from a list. As in change the "-" in its designated spot with the letter that the user guessed when the letter that is guessed is in the random word that the computer has generated.

Asked By: Joonathan01

||

Answers:

I think what you’re looking for is something like this:

word = "apple" # example output from your list
displayed_word = "-"*len(word) # make a string the same length of the word that shows guessed letters

def make_guess(s: str, guess: str, displayed_word: str) -> str:
        # convert the displayed word to a list so that it is mutable (allows us to change characters)
        displayed_word = list(displayed_word)

        # loop through the string you are guessing, s, one character at a time.
        for i, letter in enumerate(s):
            if letter == guess: # if the current letter in s matches the guess, reveal that letter.
                displayed_word[i] = letter

        return "".join(displayed_word) # finally convert the displayed word back into a string.

displayed_word = make_guess(word, "p", displayed_word) 
print(displayed_word) # outputs: "-pp--"
displayed_word = make_guess(word, "e", displayed_word) 
print(displayed_word) # outputs: "-pp-e"

Check the documentation for replace for information about how to use str.replace, as it doesn’t replace characters at a specific index as you might have misunderstood, I hope this helps.

Answered By: fishcakes
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.