字符串对象不支持项目分配

时间:2019-10-26 23:31:03

标签: python python-3.x string

我正在尝试使用Python(控制台)创建子手游戏。我遇到了无法将字符串的特定索引分配给新值的问题。我收到以下错误:

builtins.TypeError: 'str' object does not support item assignment

这是我的子手游戏的代码。有什么方法可以将字符串的索引重新分配给新值?

# Hangman Game

import random

# A list of possible words for the game
dictionary = ["Apple", "Orange", "Car", "Python", "Programming", "Bicycle", "Scooter"]
game_end = False
word = dictionary[random.randint(0, 7)]
unknown_word = "-" * len(word)
damage = 0

# Main game loop
while not game_end:
    # Asks player to guess a letter
    print("Your word is:\n" + unknown_word)
    guess = input("Enter a letter here:")
    # Checks if the letter guessed is in the word
    count = 0
    for letter in word:
        if guess == letter:
            word[count] = letter # Error is here
        else:
            count += 1
            damage += 1
    # Checks if the damage variable (from incorrect guesses) exceeds a certain number which ends the game
    if damage >= len(unknown_word * len(unknown_word)) + 5:
        print("You lose!")
        game_end = True
    # Checks if the player has guessed all the letter/the whole word
    elif unknown_word == word:
        print("You win.")
        print("Your word is:\n" + unknown_word)
        game_end = True
    else:
        continue

0 个答案:

没有答案