0

I am currently completely new to python and trying to build a simple hangman game. I created a .txt file with all the sample words and imported it to python. When printing them out however they all have this format: ['exampleword\n'], ['exampleword2\n'] I however want to get rid of the \n ending. I tried most of the suggestions from this thread: How to remove '\n' from end of strings inside a list?, but they didn't work.

woerter = open("woerter.txt", "r")
wortliste = [line.split("\t") for line in woerter.readlines()]
print(wortliste)

I have python 3.8.2. installed, any help is greatly appreciated :)

3 Answers3

1

try:

woerter = open("woerter.txt", "r")
wortliste = [line.rstrip() for line in woerter.readlines()]
print(wortliste)
Gabip
  • 6,159
  • 3
  • 5
  • 19
0

no reason to use readlines, you can just iterate over the file directly:

with open('woerter.txt') as f:
    wortlist = [l.strip() for l in f]
acushner
  • 8,186
  • 1
  • 27
  • 30
0

You can use str.splitlines().
for example:

string = "this\n"
string += "has\n"
string += "multiple\n"
string += "lines"

words = string.splitlines()
print(words)

# Outputs: ['this', 'has', 'multiple', 'lines']
with open("woerter.txt", 'r') as f:
    wordlist = f.read().splitlines()
ori6151
  • 533
  • 5
  • 11