【问题标题】:" AttributeError: 'list' object has no attribute 'replace " showed when I ran my code“ AttributeError: 'list' object has no attribute 'replace” 当我运行我的代码时显示
【发布时间】:2020-03-25 14:29:09
【问题描述】:

这是一个刽子手游戏,我知道它还没有完成,但我被这个错误困住了 我收到错误 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() 方法是从最后第三行开始。

【问题讨论】:

  • guessed_letters 是一个列表,而不是一个字符串
  • 我认为你应该用' '.join (guessed_letters) 替换那行,就像你在开始时所做的那样
  • 说实话,我之前做的第一个 .join 不是我。那是其他人建议我这样做。你能告诉我它是如何工作的
  • 添加完整的回溯。它告诉我们的不仅仅是“得到错误”。

标签: python python-3.x methods


【解决方案1】:

列表中没有用于替换的内置方法,但它只是一个循环来进行替换,检查一下,也许对你有用:

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

【讨论】:

    猜你喜欢
    • 2022-01-10
    • 2020-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-01
    • 1970-01-01
    • 2013-09-11
    相关资源
    最近更新 更多