本文介绍了在Python中搜索并获得一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从字符串中搜索包含另一个字符串的行并检索整行?

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

例如:

string = 
    qwertyuiop
    asdfghjkl

    zxcvbnm
    token qwerty

    asdfghjklñ

retrieve_line("token") = "token qwerty"

推荐答案

您提到了整个行",所以我认为mystring是整行.

you mentioned "entire line" , so i assumed mystring is the entire line.

if "token" in mystring:
    print mystring

但是,如果您只想获取令牌qwerty",

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

这篇关于在Python中搜索并获得一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 16:35