从列表的每个元素中剥离 \n
stripping \n from every element of a list
我目前是 python 的新手,正在尝试构建一个简单的刽子手游戏。我创建了一个包含所有示例单词的 .txt 文件并将其导入 python。然而,当打印出来时,它们都具有这种格式:['exampleword\n']、['exampleword2\n'] 但是我想去掉 \n 结尾。我尝试了此线程中的大部分建议:How to remove '\n' from end of strings inside a list?,但它们没有用。
woerter = open("woerter.txt", "r")
wortliste = [line.split("\t") for line in woerter.readlines()]
print(wortliste)
我有 python 3.8.2。已安装,非常感谢任何帮助:)
尝试:
woerter = open("woerter.txt", "r")
wortliste = [line.rstrip() for line in woerter.readlines()]
print(wortliste)
没有理由使用readlines
,你可以直接遍历文件:
with open('woerter.txt') as f:
wortlist = [l.strip() for l in f]
您可以使用 str.splitlines()
.
例如:
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()
我目前是 python 的新手,正在尝试构建一个简单的刽子手游戏。我创建了一个包含所有示例单词的 .txt 文件并将其导入 python。然而,当打印出来时,它们都具有这种格式:['exampleword\n']、['exampleword2\n'] 但是我想去掉 \n 结尾。我尝试了此线程中的大部分建议:How to remove '\n' from end of strings inside a list?,但它们没有用。
woerter = open("woerter.txt", "r")
wortliste = [line.split("\t") for line in woerter.readlines()]
print(wortliste)
我有 python 3.8.2。已安装,非常感谢任何帮助:)
尝试:
woerter = open("woerter.txt", "r")
wortliste = [line.rstrip() for line in woerter.readlines()]
print(wortliste)
没有理由使用readlines
,你可以直接遍历文件:
with open('woerter.txt') as f:
wortlist = [l.strip() for l in f]
您可以使用 str.splitlines()
.
例如:
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()