Python 'str' object does not support item assignment error Duplicate

Asked 2 years ago, Updated 2 years ago, 45 views

(One answer) Last year

I'm studying using a book, but I get an error even if I write the code according to the book.
This code is like a word guessing game in which you type the alphabet one letter at a time, and if a hidden word has the alphabet, that part becomes clear.

The error does not always occur, and works fine when the word you enter is not included in the hidden word (cat in the code below), but the error 'str' object does not support item assignment appears when you enter any of the c,a,t characters.

What is the cause?I'm sorry if I don't have enough words.Thank you.
Here is the code.
  

def hangman(word):
    wrong = 0
    stages=[",
              "________        ",
              "|               ",
              "|       |       ",
              "|       〇      ",
              "|      /|/     ",
              "|      / /      ",
              "|               ",
              ]
    rletters=list(word)
    board="_"*len(word)
    win=False
    print("Welcome to Hangman!")

    while long<len(stages)-1:
        print("\n")
        msg="Expect one letter!"
        char=input(msg)
        if char in letters:
            cind=rletters.index(char)
            print(cind)
            board [cind] = char
            rletters [cind] = "$"
        else:
            wrong + = 1
        print("".join(board))
        e=wrong+1
        print("\n".join(stages[0:e]))
        if "_" not in board:
            print("You win")
            print("".join(board))
            win=True
            break
    if not win:
        print("\n".join(stages[0:wrong+1]))
        print("You lost! The answer is {}.".format(word))

hangman ("cat")

python python3

2022-09-30 11:41

2 Answers

Source description and:

cind=rletters.index(char)
print(cind)
board [cind] = char
rletters [cind] = "$"

If you look at this when outputting the results:

print("".join(board))

Wrong board is a string in this description:

board="_"*len(word)

Just like rletters=list(word) above it, listing is probably the least modified.

board=list("_"*len(word))


2022-09-30 11:41

board [cind] = char

 board = board [:cind] + char + board [cind+1:]

What if?

The former method of substitution may have been possible in Python 2, but Python 3 does not seem to be able to.


2022-09-30 11:41

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.