Python 交换列表中某行的内容(如果存在关键字)

Python 交换列表中某行的内容(如果存在关键字),python,Python,如果列表中的一行包含某个字符串,如何更改该行的内容 如果我的文件包含“请删除此项”,我想将其更改为空行 例如: for line in Thelist: if "Please Delete This" in line: line in Thelist = "\n" 您可以使用索引访问列表元素。 实现它的最简单方法是使用枚举来 在行旁边获取行索引 for i, line in enumerate(Thelist): if "Please Delete This"

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

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

例如:

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

您可以使用索引访问列表元素。 实现它的最简单方法是使用
枚举
来 在
行旁边获取行索引

for i, line in enumerate(Thelist):
    if "Please Delete This" in line:
        Thelist[i] = "\n"

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

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

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

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']

空字符串而不是换行符似乎足够了,并允许更统一的进一步处理。