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

时间:2019-08-23 14:43:37

标签: python text

我的输出(字符串):

First Line
second something aaa
MY2 asd hello
no one nothing 

我需要删除MY2之前的所有行 输出应显示为:

MY2 asd hello
no one nothing 

代码:(不起作用)

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

3 个答案:

答案 0 :(得分:1)

您可以遍历所有行,并在遇到字符串时保留标志。

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)

答案 1 :(得分:1)

具有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)

输出:

MY2 asd hello
no one nothing

答案 2 :(得分:1)

使用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] )

打印:

MY2 asd hello
no one nothing