0

I am trying to create a simple hangman game, with the goal output being like this: player chooses the letter m
Output: m______
You have found the letter m
Guesses Left: 7
Input guess
However, the output I am getting is this: You have found the letter m
"_________" (no quotations)
Guesses Left: 7
Input guess

I am wondering why _____ is not being replaced with m________

word = "mystery"
solved = 1
guesses = 7
solver = 0
o = "_______"
while solved == 1:
    print(o)
    print("Guesses Left:", guesses)
    print("Input guess")
    guess = str(input())
    x = word.find(guess)
    if x > -0.5:
        print("You have found the letter", guess)
        z = o[x:x]
        o.replace(_, guess)
        solver = solver + 1
        if solver == 7:
            print("YOU WON!!!!")
            solved = 2
    else:
        guesses = guesses - 1
        if guesses == 0:
            print("Out of lives...")
            solved == 0

Thanks!

2 Answers 2

1

since strings are immutable in python, when you call o.replace(_,guess), replace will actually create another instance of a string that has the necessary replacements. You thus need to assign the return value back to o like this:

o=o.replace('_',guess)

ALSO:

o.replace will actually replace EVERY instance of the first string with the second, which is probably not your expected output. I would instead use this line:

o = o[0:x-1] + guess + [-x-1:-1]

SIDE NOTE:

this will only work if there is only one occurrence of the guess, there are a lot of things you can do to make this hangman game mroe verbose (multiple letter occurrences, inputs that are more than a letter, etc)

Sign up to request clarification or add additional context in comments.

Comments

0

Here is the problem

o.replace(_, guess)

returns the replaced value but o never changes.

right way to change the var:

o = o.replace("_", guess)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.