Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing linebreaks in python?

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.

From my initial research, I think I need to use r.string() to remove it. However, I'm not sure where it would go.

Sorry for the newbie question.

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

print (secretWord)
like image 666
jamyn Avatar asked Oct 20 '25 04:10

jamyn


1 Answers

The other answers are better in my opinion, but you can also use:

secretWord = secretWord.replace('\n', ''))

EDIT: OP stated secretWord is a list, not a string.

In the case of a list of strings, use:

secretWord = [each.replace('\n', '') for each in secretWord]
like image 192
Kevin D Avatar answered Oct 26 '25 19:10

Kevin D



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!