Search and get a line in Python

前端 未结 4 1303
暖寄归人
暖寄归人 2021-02-05 03:26

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

For example:

string = 
    qwertyuiop
    asdfghj         


        
4条回答
  •  甜味超标
    2021-02-05 04:05

    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
    

提交回复
热议问题