我运行代码时显示的“ AttributeError:'list'对象没有属性'replace'

时间:2020-03-25 14:29:09

标签: python python-3.x methods

这是一个子手游戏,我知道还没有完成,但是我被卡在这个错误上 我收到错误AttributeError: 'list' object has no attribute 'replace'

代码:

import random
word_list_easy = ["word", "apple", "banana", "cheese"]
difficulty = str(input("Please enter difficulty: Easy, Medium or Hard. "))
difficulty = difficulty.upper()
empty = ("")
if difficulty == ("EASY"):
    maximum = len(word_list_easy)
    maximum = maximum - 1
    #makes a random variable that cant excede the length of the list
    random = random.randint(0,maximum)
    random_word = word_list_easy[random]
    #chooses a random word in the list
    word_length = len(random_word)
    guessed_letters = ['_'] * word_length
    print('  ' + ' '.join (guessed_letters))
    print("There are ", word_length ,"letters in the word")
    #sets how many tries you get. (later will make graphical)
    tries = 5
    while tries >= 1:
        #will repeat untill out of tries
        guessed_letter = input("Enter your guess of the letter ")
        while len(guessed_letter) > 1:
                  guessed_letter = input("Enter one letter that you think is in the word ")
        while (guessed_letter) == (""):
            guessed_letter = input("Please enter a letter ")
                  #if the letter is in the word
        new_random_word = random_word.replace(guessed_letter, empty)
        if (guessed_letter) in (random_word):
            print("You guessed correctly")
            #find the length of the new word to repeat the "_" lines for length of new word
            for index in range (word_length):
                if guessed_letter == random_word [index]:
                    guessed_letters[index] = guessed_letter
            print (" " + " ".join (guessed_letters))
        else:
            print("Sorry but your guess was wrong ")
            tries = tries - 1
            print("You have",tries," tries left")
            print (guessed_letters)
        check_word = guessed_letters.replace(" ", "")
        if check_word == random_word:
            print("Congratulations, you managed to complete the word. Maybe try a higher difficulty next time ")

这是什么意思,我在做什么错以及如何解决。 replace()方法是从第三行开始。

1 个答案:

答案 0 :(得分:1)

列表中没有内置的替换方法,但这只是一个循环,可以进行替换,检查它,也许对您有用:

check_word = [x.strip() for x in guessed_letters]
check_word = "".join(check_word)