简体   繁体   English

在特定字符串开始python之前删除所有行

[英]Remove all lines before specific string starts python

My output (string): 我的输出(字符串):

First Line
second something aaa
MY2 asd hello
no one nothing 

I need to remove all linesw before MY2 Output should looks line : 我需要先删除所有linew,然后MY2输出应显示为line:

MY2 asd hello
no one nothing 

code: (not working) 代码:(不起作用)

output= '\n'.join(output.split('\n'))
for line in output:
    a=output.strip()=='MY2'
    print(a)

You can traverse through all the lines, and keep the flag if string encountered. 您可以遍历所有行,并在遇到字符串时保留标志。

output = """First Line
second something aaa
MY2 asd hello
no one nothing """

set_print = False
for line in output.split('\n'):
    if line.startswith('MY2'):
        set_print = True
    if set_print:
        print(line)

With itertools.dropwhile feature: 使用itertools.dropwhile功能:

from itertools import dropwhile

output = '''First Line
second something aaa
MY2 asd hello
no one nothing'''

for l in dropwhile(lambda s: not s.startswith('MY2'), output.splitlines()):
    print(l)

The output: 输出:

MY2 asd hello
no one nothing

Another solution, using re module ( regex101 ): 另一个解决方案,使用re模块( regex101 ):

output = '''First Line
second something aaa
MY2 asd hello
no one nothing'''

import re

print( re.findall(r'^(MY2.*)', output, flags=re.S|re.M)[0] )

Prints: 打印:

MY2 asd hello
no one nothing

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

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