如果该行包含某个字符串,如何更改列表中某行的内容?
如果我的文件包含“请删除此”,我想将其更改为空白行。
例如:
for line in Thelist:
if "Please Delete This" in line:
line in Thelist = "\n"
答案 0 :(得分:1)
您可以使用索引访问列表元素。
最简单的方法是使用enumerate
在line
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']