Ben Ben - 1 month ago 5
Python Question

Search and get a line in Python

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

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
Comments