2 回答
TA贡献1811条经验 获得超4个赞
尝试使用enumerate,enumerate在循环时获取索引,因此我获取索引并通过索引和切片获取其余值:
for i,line in enumerate(paragraph):
if 'mom' in line:
print(paragraph[:i])
print(paragraph[i:])
编辑:
with open('file.txt','r') as f:
input_file = f.readlines()
for i,line in enumerate(input_file):
line=line.rstrip()
if 'mom' in line:
print(paragraph[:i])
print(paragraph[i:])
TA贡献1780条经验 获得超3个赞
试试这个:
import re
paragraph = ["my name is dharshini", "my mom name is chandra", "my dad name is uday" , "my anniversay is on 04/01/1997" ]
#set a flag for later
print_next = False
for line in paragraph:
find_line = re.findall(r'(mom)', line)
#if mom is found dad will be next
if print_next:
print(line)
print_next = False
#if mom is found
if len(find_line) > 0:
print(line)
print_next = True
添加回答
举报