首页 > 解决方案 > 从列表的每个元素中剥离 \n

问题描述

我目前对 python 完全陌生,并试图构建一个简单的刽子手游戏。我创建了一个包含所有示例单词的 .txt 文件并将其导入 python。然而,当它们打印出来时,它们都具有这种格式: ['exampleword\n'], ['exampleword2\n'] 但是我想摆脱 \n 结尾。我尝试了这个线程的大部分建议:如何从列表中的字符串末尾删除 '\n'?,但他们没有工作。

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

我有 python 3.8.2。已安装,非常感谢任何帮助:)

标签: pythonpython-3.8

解决方案


尝试:

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

推荐阅读