Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" 
like image 833
Ben Avatar asked Apr 01 '10 02:04

Ben


People also ask

What is find () in Python?

The find() method finds the first occurrence of the specified value. The find() method returns -1 if the value is not found. The find() method is almost the same as the index() method, the only difference is that the index() method raises an exception if the value is not found. ( See example below)

How do you print a line by line in Python?

Using end keyword # print each statement on a new line print("Python") print("is easy to learn.") # new line print() # print both the statements on a single line print("Python", end=" ") print("is easy to learn. ")


1 Answers

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 
like image 62
ghostdog74 Avatar answered Sep 28 '22 11:09

ghostdog74