user8560167
user8560167

Reputation:

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 :

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)

Upvotes: 1

Views: 917

Answers (3)

Andrej Kesely
Andrej Kesely

Reputation: 195543

Another solution, using re module (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

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92874

With itertools.dropwhile feature:

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

Upvotes: 0

harshil9968
harshil9968

Reputation: 3244

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)

Upvotes: 0

Related Questions