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)
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()
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.

Comments

0

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

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)

Comments

Your Answer

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.