2017-05-19 32 views
0

我有如下所示的變量輸出「var1」。搜索開始字符串和搜索結束字符串,然後打印python中開始到結束行之間的所有行

load: load1 
a: apples 
b: banana 
c: oranges 
d: grapes 

load: load2 
a: pen 
b: paper 
c: books 

我想要的是找到第一個字符串,它是「載:裝入1」,找到最後一個字符串
「d:葡萄」,並打印以下線的線。

load: load1 
a: apples 
b: banana 
c: oranges 
d: grapes 

爲了達到這個目的,我使用了「begin」和「end」命令。如何使用python完成它?

+0

寫您的變量的樣子完全相同:它是一個字符串或字典 –

+1

還提供代碼 –

+0

它的可變和我將從命令輸出獲得 – pioltking

回答

0

你可以這樣做(假設你從文件加載):

start_line = "load: load1" 
end_line = "d: grapes" 
print_lines = False 

with open('input.txt' , 'r') as f: 
    for line in f: 
     line = line.rstrip() 
     if line == start_line: 
      print_lines = True 
     if print_lines: 
      print line 
     if line == end_line: 
      print_lines = False 
      # Could add a break here if you wanted to do nothing with 
      # the rest of the file; e.g: 
      # break 
+1

工作,非常感謝 – pioltking

相關問題