[英]Remove all lines before specific string starts python
我的輸出(字符串):
First Line
second something aaa
MY2 asd hello
no one nothing
我需要先刪除所有linew,然后MY2
輸出應顯示為line:
MY2 asd hello
no one nothing
代碼:(不起作用)
output= '\n'.join(output.split('\n'))
for line in output:
a=output.strip()=='MY2'
print(a)
您可以遍歷所有行,並在遇到字符串時保留標志。
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)
使用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
另一個解決方案,使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.