40

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

        asdfghjklf
        
    """;
    retrieve_line("token") = "token qwerty"
Community
  • 1
  • 1
Ben
  • 16,275
  • 9
  • 45
  • 63

4 Answers4

56

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
viam0Zah
  • 25,949
  • 8
  • 77
  • 100
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
39

If you prefer a one-liner:

matched_lines = [line for line in my_string.split('\n') if "substring" in line]
Mark Lodato
  • 50,015
  • 5
  • 41
  • 32
11

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
YOU
  • 120,166
  • 34
  • 186
  • 219
9
items=re.findall("token.*$",s,re.MULTILINE)
>>> for x in items:

you can also get the line if there are other characters before token

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

The above works like grep token on unix and keyword 'in' or .contains in python and C#

s='''
qwertyuiop
asdfghjkl

zxcvbnm
token qwerty

asdfghjklñ
'''

http://pythex.org/ matches the following 2 lines

....
....
token qwerty