python - " AttributeError: 'list' object has no attribute 'replace " showed when I ran my code
问题描述
Its a hangman game and I know it isn't done, but I'm stuck on this error
I'm getting the error AttributeError: 'list' object has no attribute 'replace'
the code:
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 ")
what does this mean and what am I doing wrong and how to fix it. The replace() method is From the end the third line.
解决方案
There’s nothing built-in method for replacement in lists, but it’s just a loop to do the replacement, check it, maybe worked for you:
check_word = [x.strip() for x in guessed_letters]
check_word = "".join(check_word)
推荐阅读
- visual-studio - 如何在 Visual Studio 中更改 Peek Definition 窗口的默认大小?
- java - 将已处理文件从一个文件夹移动到 flink 中的另一个文件夹
- flutter - Flutter pageview,在运行时添加新元素
- python - Kedro:ValueError:管道不包含名为 ['preprocess_companies_node'] 的节点
- flutter - 如何获取列表中小部件的索引?
- cpanel - 用于阻止 API 调用的 Cpanel Hooks
- arduino - 无法在串行通信中读取数组(pyserial)
- loopbackjs - 如何列出 Loopback 4 中的所有路由、控制器、存储库或模型?
- kendo-ui - 将文本添加到 kendo 调度程序标题区域
- python - 在两个数字上显示以下算术运算的输出