2013-04-02 132 views
1

我正在研究一个简单的python游戏,玩家试图猜测包含在单词中的字母。问题在于,当我打印一个单词时,它会在最后打印\ n。python属性错误?

它看起来像我需要使用.strip将其删除。但是,如以下代码所示,当我使用它时,出现属性错误,表明列表对象没有属性“strip”。

对不起,这个新手问题。

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

print (secretWord) 
+0

看到,因为你已经[解决了这个问题](http://stackoverflow.com/questions/15775920/letter-guessing-game-in-python),如果你接受了这个帮助你的答案,那将会很好。 –

回答

1

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

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

当然,如果你使用的choice代替sample这将是更容易/清洁剂,因为你只抓住了一个字:

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

权。 Python中的字符串不是列表 - 你必须在两者之间进行转换(尽管它们通常表现相似)。

如果您想转字符串列表转换为字符串,你可以加入对空字符串:

x = ''.join(list_of_strings) 

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

+0

真棒,谢谢 – jamyn

0

print增加一个换行符。您需要使用一些较低级别的,像os.write

+0

这不是他遇到的问题;他看到''\ n'因为'secretWord'是一个列表而不是一个字符串。 –

0

random.sample()会返回一个列表,它看起来像你正试图随机从列表中选择一个元素,所以你应该使用random.choice()代替:

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

print (secretWord)