在Python中搜索并获取一行

40 投票
4 回答
183295 浏览
提问于 2025-04-15 21:06

有没有办法从一个字符串中查找包含另一个字符串的那一整行,并把整行内容提取出来呢?

举个例子:

    string = """
        qwertyuiop
        asdfghjkl
    
        zxcvbnm
        token qwerty

        asdfghjklf
        
    """;
    retrieve_line("token") = "token qwerty"

4 个回答

11

使用正则表达式

import re
s="""
    qwertyuiop
    asdfghjkl

    zxcvbnm
    token qwerty

    asdfghjklñ
"""
>>> items=re.findall("token.*$",s,re.MULTILINE)
>>> for x in items:
...     print x
...
token qwerty
40

如果你喜欢一句话解决问题:

matched_lines = [line for line in my_string.split('\n') if "substring" in line]
56

你提到“整行”,所以我假设mystring就是整行的内容。

if "token" in mystring:
    print(mystring)

不过如果你只是想获取“token qwerty”,

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

撰写回答