TypeError: 'str' object does not support item assignment

0

I made my "version" of a game I saw in a book.

def hangman(a):
    stages = ["",
             "________        ",
             "|               ",
             "|        |      ",
             "|        0      ",
             "|       /|\     ",
             "|       / \     ",
             "|               "
    ]

    wrong = 0
    board = "__" * len(a)
    letters = list(a)
    win = False
    print("Welcome to the Hangman game")
    while (wrong < (len(stages) - 1)):
        print ("\n")
        msg = "Guess a letter: "
        user_choice = input(msg)
        if user_choice in letters:
            i = letters.index(user_choice)
            board[i] = user_choice
            letters[i] = '$'

        else:
            wrong += 1
        print((" ".join(board)))
        e = wrong + 1
        print("\n"
              .join(stages[0:e]))
        if "__" not in board:
            win = True
            print ("You won")
            print(" ".join(board))
            break

    if not win:
        print("\n"
              .join(tages[0:wrong]))
        print("It was %s, you lose" %(a))


import random
words = ["yellow", "blue", "black", "green", "gray", "white", "gray", "orange"]
a = random.choice(words)
hangman(a)

However, when playing the game, I receive the following error when typing some letters to play:

Traceback (most recent call last):
File "C:/Users/Luiz Fernando/Desktop/PYTHON/magam2.py", line 46, in <module> hangman(a)
File "C:/Users/Luiz Fernando/Desktop/PYTHON/magam2.py", line 22, in hangman
board[i] = user_choice
TypeError: 'str' object does not support item assignment
    
asked by anonymous 14.03.2017 / 20:34

1 answer

0

The problem is that you are modifying a String, which is an immutable object in python.

Try changing the line:

board = "__" * len(a)

To:

board = ["__" for _ in range(len(a))]

or to:

board = ["__"] * len(a)

In this way, the line:

board[i] = user_choice

Modify a list, which is a changeable type.

    
14.03.2017 / 22:06