我正在开发一个简单的Python游戏,玩家尝试猜测单词中包含的字母。问题是,当我打印一个单词时,它在末尾打印\n。
看来我需要使用 .strip 来删除它。但是,当我使用它(如以下代码所示)时,我收到属性错误,指出列表对象没有属性“strip”。
抱歉这个新手问题。
import random
with open('wordlist.txt') as wordList:
secretWord = random.sample(wordList.readlines(), 1).strip()
print (secretWord)
最佳答案
嗯,那是因为列表没有名为 strip
的属性。如果您尝试print SecretWord
,您会注意到它是一个列表
(长度为1),而不是字符串
。您需要访问该列表中包含的字符串,而不是列表本身。
secretWord = random.sample(wordList.readlines(), 1)[0].strip()
当然,如果您使用 choice
而不是 sample
,这会更容易/更清晰,因为您只抓取一个单词:
secretWord = random.choice(wordList.readlines()).strip()
关于python 属性错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15774979/