Search and get a line in Python

Ben picture Ben · Apr 1, 2010 · Viewed 124.8k times · Source

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"

Answer

ghostdog74 picture ghostdog74 · Apr 1, 2010

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