views:

71

answers:

3

Is there a way to search, from a string, a line containing another string and retrieve the entire line?

For example:

string = 
    qwertyuiop
    asdfghjkl

    zxcvbnm
    token qwerty

    asdfghjklñ

retrieve_line("token") = "token qwerty"

+1  A: 

With regular expressions

import re
s="""
    qwertyuiop
    asdfghjkl

    zxcvbnm
    token qwerty

    asdfghjklñ
"""
>>> items=re.findall("token.*$",s,re.MULTILINE)
>>> for x in items:
...     print x
...
token qwerty
S.Mark
+5  A: 

you mentioned "entire line" , so i assumed mystring is the entire line.

if "token" in mystring:
    print mystring

however if you want to just get "token qwerty",

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

If you prefer a one-liner:

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