如何在Python中的字符串中修剪/删除“ \ n”

时间:2019-03-22 07:53:47

标签: python

我有疑问。我是Python的新手

让我们说我有一个文件in.txt。在此文件中,我的名字如下所示。

Sunday

Monday

Tuesday
.
.

我想将它们放入列表,我在做

#!/usr/bin/python3
with open("in.txt") as f:
lines = f.readlines()
lines = [l for l in lines]
print (lines);

输出为:

['Sunday\n', 'Monday\n', 'Tuesday\n']

我想像这样打印它:

['Sunday', 'Monday', 'Tuesday']

我将如何删除\n

任何建议都会有很大帮助,我尝试rstrip()无效。

3 个答案:

答案 0 :(得分:1)

尝试一下:

lines = [l.strip() for l in lines]

答案 1 :(得分:1)

它应该与rstrip()甚至strip()一起使用,就像这样:

with open("in.txt") as f:
    lines = f.readlines()

lines = [l.rstrip() for l in lines]
print (lines)

或更简洁地说:

with open("in.txt") as f: 
    lines = [line.rstrip() for line in f]

答案 2 :(得分:1)

rstrip使用列表理解:

with open("in.txt") as f:
    lines = [i.rstrip() for i in f]
print(lines)

输出:

['Sunday', 'Monday', 'Tuesday']