简体   繁体   English

搜索开始字符串和搜索结束字符串,然后在python中打印开始到结束行之间的所有行

[英]search begin string and search end string then print all lines between begin to end lines in python

I have variable output "var1" like below. 我有如下所示的变量输出“ var1”。

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

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

What i want is find first string that is "load: load1" and find last string 我想要的是找到第一个字符串“ load:load1”并找到最后一个字符串
"d: grapes" and print the lines below lines. “ d:葡萄”,并在行下方打印行。

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

To serve this purpose i was using "begin" and "end" commands. 为了达到这个目的,我使用了“ begin”和“ end”命令。 How get it done using python? 如何使用python完成它?

You could do something like (assuming you're loading from a file): 您可以执行以下操作(假设您正在从文件中加载):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM