2010-04-01 72 views
12

有沒有一種方法可以從字符串中搜索包含另一個字符串的行並檢索整行?在Python中搜索並獲取一行

例如:

string = 
    qwertyuiop 
    asdfghjkl 

    zxcvbnm 
    token qwerty 

    asdfghjklñ 

retrieve_line("token") = "token qwerty" 

回答

25

你提到 「整行」,所以我估計MyString的是整條生產線。

if "token" in mystring: 
    print mystring 
但是如果你只想得到 「令牌QWERTY」

>>> mystring=""" 
...  qwertyuiop 
...  asdfghjkl 
... 
...  zxcvbnm 
...  token qwerty 
... 
...  asdfghjklñ 
... """ 
>>> for item in mystring.split("\n"): 
... if "token" in item: 
...  print item.strip() 
... 
token qwerty 
3

使用正則表達式

import re 
s=""" 
    qwertyuiop 
    asdfghjkl 

    zxcvbnm 
    token qwerty 

    asdfghjklñ 
""" 
>>> items=re.findall("token.*$",s,re.MULTILINE) 
>>> for x in items: 
...  print x 
... 
token qwerty 
15

如果你喜歡一個班輪:

matched_lines = [line for line in my_string.split('\n') if "substring" in line] 
+0

我不小心按下了匹配「downvote」按鈕!我想我需要等待upvoting它,或者可能需要首先進行編輯,然後才能糾正我的錯誤。 – 2015-05-09 09:07:18

3
items=re.findall("token.*$",s,re.MULTILINE) 
>>> for x in items: 

,你還可以得到線如果在令牌之前還有其他字符

items=re.findall("^.*token.*$",s,re.MULTILINE) 

上述工程等上UNIX的grep令牌和關鍵字 '中' 或在python。載和C#

s=''' 
qwertyuiop 
asdfghjkl 

zxcvbnm 
token qwerty 

asdfghjklñ 
''' 

http://pythex.org/ 以下2行

.... 
.... 
token qwerty