1

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)
jamyn
  • 1,483
  • 3
  • 14
  • 13
  • Seeing as you've [solved this problem](http://stackoverflow.com/questions/15775920/letter-guessing-game-in-python), it would be nice if you Accepted the answer here that helped you. – Henry Keiter Apr 02 '13 at 23:06

4 Answers4

1

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()
Henry Keiter
  • 16,324
  • 7
  • 47
  • 78
0

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.

Rafe Kettler
  • 73,388
  • 19
  • 151
  • 149
0

print adds a newline. You need to use something lower level, like os.write

Falmarri
  • 46,415
  • 39
  • 146
  • 189
0

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)
Andrew Clark
  • 192,132
  • 30
  • 260
  • 294