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)
asked Apr 2, 2013 at 21:44
1
  • Seeing as you've solved this problem, it would be nice if you Accepted the answer here that helped you. Commented Apr 2, 2013 at 23:06

4 Answers 4

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()
answered Apr 2, 2013 at 21:47
Sign up to request clarification or add additional context in comments.

Comments

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.

answered Apr 2, 2013 at 21:47

Comments

0

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

answered Apr 2, 2013 at 21:47

1 Comment

This isn't the problem he's having; he's seeing the '\n' because secretWord is a list instead of a string.
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)
answered Apr 2, 2013 at 21:48

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.