在Python中搜索并获取一行

Ben*_*Ben 18 python string search line

有没有办法从字符串中搜索包含另一个字符串的行并检索整行?

例如:

string = 
    qwertyuiop
    asdfghjkl

    zxcvbnm
    token qwerty

    asdfghjklñ

retrieve_line("token") = "token qwerty"
Run Code Online (Sandbox Code Playgroud)

gho*_*g74 34

你提到"整行",所以我假设mystring是整行.

if "token" in mystring:
    print mystring
Run Code Online (Sandbox Code Playgroud)

但是如果你想得到"令牌qwerty",

>>> mystring="""
...     qwertyuiop
...     asdfghjkl
...
...     zxcvbnm
...     token qwerty
...
...     asdfghjklñ
... """
>>> for item in mystring.split("\n"):
...  if "token" in item:
...     print item.strip()
...
token qwerty
Run Code Online (Sandbox Code Playgroud)


Mar*_*ato 29

如果你喜欢单行:

matched_lines = [line for line in my_string.split('\n') if "substring" in line]
Run Code Online (Sandbox Code Playgroud)


Roh*_*kar 7

items=re.findall("token.*$",s,re.MULTILINE)
>>> for x in items:
Run Code Online (Sandbox Code Playgroud)

如果令牌之前还有其他字符,您也可以获取该行

items=re.findall("^.*token.*$",s,re.MULTILINE)
Run Code Online (Sandbox Code Playgroud)

上面的工作类似于unix上的grep标记和python和C#中的关键字'in'或.contains

s='''
qwertyuiop
asdfghjkl

zxcvbnm
token qwerty

asdfghjklñ
'''
Run Code Online (Sandbox Code Playgroud)

http://pythex.org/ 匹配以下2行

....
....
token qwerty
Run Code Online (Sandbox Code Playgroud)


YOU*_*YOU 5

使用正则表达式

import re
s="""
    qwertyuiop
    asdfghjkl

    zxcvbnm
    token qwerty

    asdfghjklñ
"""
>>> items=re.findall("token.*$",s,re.MULTILINE)
>>> for x in items:
...     print x
...
token qwerty
Run Code Online (Sandbox Code Playgroud)