Python 从输出变量中搜索字符串并打印下两行 [英] Python search string from output variable and print next two lines

查看:44
本文介绍了Python 从输出变量中搜索字符串并打印下两行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从命令输出中搜索字符串并打印输出中的下两行.

How do I Search string from command output and print next two lines from the output.

代码如下:

a = """
Some lines I do not want 
----- -------- --
I need this line
I need this line also
Again few lines i do not want
"""
for line in a.split("\n"):
    if line.startswith("----"):
        print "I need this line"
        print "I need this line also"

我在上面的代码中所做的是检查行是否以----"开头,这工作正常.现在如何在以----"开头的行之后打印两行.在这个示例代码打印中,我需要这一行,我也需要这一行"

What I am doing in above code is I am checking if line starts with "----" and This works fine. Now How do i print exactly two lines after line starts with "----". In this example code print, " I need this line and I need this line also"

推荐答案

您可以从列表中创建一个迭代器(BTW 不需要文件句柄).然后让 for 迭代,但允许在循环中手动使用 next :

you can create an iterator out of the list (no need with a file handle BTW). Then let for iterate, but allow to use next manually within the loop:

a = """
Some lines I do not want
----- -------- --
I need this line
I need this line also
Again few lines i do not want
"""
my_iter = iter(a.splitlines())
for line in my_iter:
    if line.startswith("----"):
        print(next(my_iter))
        print(next(my_iter))

如果破折号后没有足够的行,此代码将引发 StopIteration.避免此问题的一种替代方法是(由 Jon Clements 提供)

This code will raise StopIteration if there aren't enough lines after the dashes. One alternative that avoids this issue is (courtesy Jon Clements)

from itertools import islice

my_iter = iter(a.splitlines(True))  # preserves \n (like file handle would do)
for line in my_iter:
    if line.startswith("----"):
        print(''.join(islice(my_iter, 2)))

另一种方式,不拆分字符串:

Another way, without splitting the string:

print(re.search("-----.*\n(.*\n.*)",a).group(1))

这将在 未拆分 多行字符串中搜索模式后的 2 行.如果 re.search 返回 None 可能会崩溃,因为 没有 没有更多的行了.

this searches for 2 lines after the pattern in the unsplitted, multi-line string. Can crash if re.search returns None because there are no more lines.

在这两种情况下你都会得到:

In both cases you get:

I need this line
I need this line also

这篇关于Python 从输出变量中搜索字符串并打印下两行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆