【问题标题】:python attribute error?python属性错误?
【发布时间】:2013-04-02 21:44:11
【问题描述】:

我正在开发一个简单的 python 游戏,玩家试图猜测单词中包含的字母。问题是,当我打印一个单词时,它会在末尾打印 \n。

看来我需要使用 .strip 来删除它。但是,当我按照下面的代码使用它时,我收到一个属性错误,指出列表对象没有属性“strip”。

对不起,新手问题。

import random
with open('wordlist.txt') as wordList:
    secretWord = random.sample(wordList.readlines(), 1).strip()

print (secretWord)

【问题讨论】:

  • 看到你已经solved this problem,如果你在这里接受了对你有帮助的答案,那就太好了。

标签: python attributes


【解决方案1】:

嗯,这是因为列表没有名为strip 的属性。如果您尝试print secretWord,您会注意到它是list(长度为1),而不是string。您需要访问该列表中包含的字符串,而不是列表本身。

secretWord = random.sample(wordList.readlines(), 1)[0].strip()

当然,如果您使用choice 而不是sample,这会更容易/更干净,因为您只抓住一个词:

secretWord = random.choice(wordList.readlines()).strip()

【讨论】:

    【解决方案2】:

    没错。 Python 中的字符串不是列表——您必须在两者之间进行转换(尽管它们的行为通常相似)。

    如果你想把一个字符串列表变成一个字符串,你可以加入空字符串:

    x = ''.join(list_of_strings)
    

    x 现在是一个字符串。你必须做一些类似的事情才能从random.sample(一个列表)中得到一个字符串。

    【讨论】:

      【解决方案3】:

      print 添加一个换行符。您需要使用较低级别的内容,例如os.write

      【讨论】:

      • 这不是他遇到的问题;他看到的是'\n',因为secretWord 是一个列表而不是一个字符串。
      【解决方案4】:

      random.sample() 将返回一个列表,看起来您正试图从列表中随机选择一个元素,因此您应该改用random.choice()

      import random
      with open('wordlist.txt') as wordList:
          secretWord = random.choice(wordList.readlines()).strip()
      
      print (secretWord)
      

      【讨论】: