I'm working on a simple python game in which the player attempts to guess letters contained in a word. The problem is, when I print a word, it's printing the \n at the end.
It looks like I need to use .strip to remove it. However, when I use it as seen in the following code, I get an attribute error saying that the list object has no attribute "strip".
Sorry for the newbie question.
import random
with open('wordlist.txt') as wordList:
secretWord = random.sample(wordList.readlines(), 1).strip()
print (secretWord)
-
Seeing as you've solved this problem, it would be nice if you Accepted the answer here that helped you.Henry Keiter– Henry Keiter2013年04月02日 23:06:57 +00:00Commented Apr 2, 2013 at 23:06
4 Answers 4
Well, that's because lists don't have an attribute named strip. If you try print secretWord you'll notice that it's a list (of length 1), not a string. You need to access the string contained in that list, rather than the list itself.
secretWord = random.sample(wordList.readlines(), 1)[0].strip()
Of course, this would be much easier/cleaner if you used choice instead of sample, since you're only grabbing one word:
secretWord = random.choice(wordList.readlines()).strip()
Comments
Right. Strings in Python are not lists -- you have to convert between the two (though they often behave similarly).
If you'd like to turn a list of string into a string, you can join on the empty string:
x = ''.join(list_of_strings)
x is now a string. You'll have to do something similar to get from what you got out of random.sample (a list) to a string.
Comments
random.sample() will return a list, it looks like you are trying to randomly select a single element from the list so you should use random.choice() instead:
import random
with open('wordlist.txt') as wordList:
secretWord = random.choice(wordList.readlines()).strip()
print (secretWord)