Is there a way to replace a character in a certain positon out of a row of many of the same character?

Category: python replace (3 Views)

I am making a hangman game and i have come across this error (vsc):

    guessoutput = guessgui[a].replace(".", guess)
TypeError: list indices must be integers or slices, not list

my code starts by printing a line of dots (ie "......") and i need to replace one of the dots with the corresponding character in the original word i have googled this and havent found any solutions for this issue

Code:


#gameset takes an input word, formats it into lowercase and prints out a line of underscores of the length of the original string via multiplication
def gameset():
    global lives
    lives = 10
    global word
    word = input()
    word = word.lower()
    global guessgui
    guessgui = ("."*len(word))
    print(guessgui)
    guessgui = list(guessgui)

def play():
    global guess
    global word
    global lives
    while True:
        guess = input()
        if word.find(guess) !=-1:
            print("Nice!")
            a = [pos for pos, char in enumerate(word) if char == guess] #finds the position/s of the guessed character/s in the original word
            guessoutput = guessgui[a].replace(".", guess)
            print(guessoutput)
        else:
            lives = lives-1
            print(f"wrong guess, you have {lives} lives left!")


gameset()   
play()
🔴 No definitive solution yet

📌 Solution 1

You can't replace multiple indexes like that. You can use a list comprehension to return a list with . replaced with the guessed character.

    while lives > 0:
        guess = input()
        if guess in word:
            print("Nice!")
            guessoutput = [wordchar if wordchar == guess else guichar for wordchar, guichar in zip(word, gui)]
            print(guessoutput)
        else:
            lives = lives-1
            print(f"wrong guess, you have {lives} lives left!")

Also use guess in word rather than word.find() to tell if there's a match.