[英]Python to search and print out the whole line just like Linux grep?
讓我們以此為例。
>>> t = '''Line 1
... Line 2
... Line 3'''
>>>
re.findall
只打印出類似於 Linux grep -o
的特定模式
>>> re.findall('2', t)
['2']
>>>
Linux grep
wolf@linux:~$ echo 'Line 2' | grep 2
Line 2
wolf@linux:~$
Linux grep -o
wolf@linux:~$ echo 'Line 2' | grep 2 -o
2
wolf@linux:~$
我知道可以打印出整個 output,我現在想不出邏輯。
Python 中的預期 Output
Line 2
如果有更好的方法可以做到這一點,請告訴我。
print([l for l in t.splitlines() if "2" in l])
或者,如果您希望它像grep
那樣分開,
print('\n'.join([l for l in t.splitlines() if "2" in l]))
t = '''Line 1
Line 2
Line 3'''
for line in t.split('\n'):
if(line.find("2")!=-1):
print(line)
這應該適用於您的用例。 find() 用於檢查字符串中是否存在模式
將.* 放在您要查找的內容周圍:
re.findall(r'.*2.*', t)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.