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條經驗 獲得超4個贊
試試這個:
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
添加回答
舉報