我有一个包含多个字符串的列表,我想在字符串的子字符串中搜索一些模式,并用python打印下一行、上一行模式

我有一个包含多个字符串的列表,我想在字符串的子字符串中搜索一些模式,并用python打印下一行、上一行模式,python,list,string-matching,Python,List,String Matching,首先从列表中,我必须检查哪些值包含start和end关键字。如果该值包含开始/结束,则应在这些值的行之间打印 输入: list1 = ['started','1','asd', 'ending of the word/n','aaaa','startin','answer','fruit','123','ending'] ['1',asd] ['answer','fruit','123'] 预期输出: list1 = ['started','1','asd', 'ending of the

首先从列表中,我必须检查哪些值包含startend关键字。如果该值包含开始/结束,则应在这些值的行之间打印

输入:

list1 = ['started','1','asd', 'ending of the word/n','aaaa','startin','answer','fruit','123','ending']
['1',asd]
['answer','fruit','123']
预期输出:

list1 = ['started','1','asd', 'ending of the word/n','aaaa','startin','answer','fruit','123','ending']
['1',asd]
['answer','fruit','123']
在此之后,我需要打印substring1和substring2变量之间的值。我不知道如何继续下去。我也是python新手。有人能帮我解决这个问题吗。提前谢谢

list1 = ['started', '1', 'asd', 'ending of the word/n', 'aaaa', 'startin', 'answer', 'fruit', '123', 'ending']
index_start = 0
for i in range(len(list1)):
    if 'start' in list1[i]:
        index_start = i
    if 'end' in list1[i]:
        print(list1[index_start+1:i])
for
循环中使用
i in range()
更合适,这样您就可以获得模式开始/结束位置的索引。然后,只要在找到“开始”时存储
start\u索引
,并在找到“结束”子字符串时打印中间的所有内容即可

当然,您需要添加一些条件,以确保在结束之前有一个开始

输出:

['1', 'asd']
['answer', 'fruit', '123']

列表1=['start'、'started'、'1'、'asd'、'n'的结尾、'start'、'end'、'end'、'aaaa'、'startin'、'answer'、'fruit'、'123'、'ending']预期输出:['1',asd]['answer'、'fruit'、'123']在这种情况下,如何跳过第7个索引值,因为在第7个索引之前没有start关键字。如我所述,提前感谢您,您必须为其他情况添加一个条件