如何从列表中的条目中删除“\n”?

2024-09-24 00:31:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经编辑了原来的问题,因为它不再相关,所以这里是新的请求:

我有一个包含以下内容的文本文件:

Sender,Date,Subject
SolarAlert <noreply@example.com>,2019-01-11,SolarAlert Alert: DATAALRT
SolarAlert <noreply@example.com>,2019-01-11,SolarAlert Alert: NETALRT
SolarAlert <noreply@example.com>,2019-01-11,SolarAlert Alert: SFOALRT

通过使用以下内容,我可以引用我需要的文本(DATAALRT、NETALRT、sfoart)。你知道吗

OPENDOC = open('Alert.txt', 'r')
READDOC = OPENDOC
for line in READDOC:
    rows = [line.split(': ', 2)[-1] for line in READDOC]
newrow = rows

print(rows)
print(rows[1])

但每行还包含一个“\n”。我该如何删除它?你知道吗

非常感谢


Tags: incom编辑forexamplelinealertrows
1条回答
网友
1楼 · 发布于 2024-09-24 00:31:08

下面的脚本读取'Alert.txt',并创建一个名为rows的变量,其值为['DATAALRT', 'NETALRT', 'SFOALRT']

rows = []
with open('Alert.txt', 'r') as READDOC:
    for line in READDOC.readlines():
        if ': ' in line:
            rows.append(line.strip().split(': ', 2)[-1])
print(rows)

But each row also includes a "\n". How would i remove that?

要删除字符串末尾的“\n”,只需使用str.strip()。你知道吗

相关问题 更多 >