如果存在关键字,则交换列表中一行的内容

时间:2018-07-17 07:17:01

标签: python

如果该行包含某个字符串,如何更改列表中某行的内容?

如果我的文件包含“请删除此”,我想将其更改为空白行。

例如:

for line in Thelist:
    if "Please Delete This" in line:
        line in Thelist = "\n"

3 个答案:

答案 0 :(得分:1)

您可以使用索引访问列表元素。 最简单的方法是使用enumerateline

旁边获取行索引
for i, line in enumerate(Thelist):
    if "Please Delete This" in line:
        Thelist[i] = "\n"

答案 1 :(得分:1)

由于Thelist是一个字符串列表,因此可以使用索引对其进行迭代,并在需要时通过索引更改其内容。

for index in range(len(Thelist)):
    if "Please Delete This" in Thelist[index]:
        Thelist[index] = '\n'

答案 2 :(得分:1)

您可以使用列表理解来完成任务:

Thelist = ['This is line 1',
           'This is line 2',
           'Please Delete This',
           'This is another line']

Thelist = ['\n' if "Please Delete This" in line else line for line in Thelist]

print(Thelist)

输出:

['This is line 1', 'This is line 2', '\n', 'This is another line']