【问题标题】:Search and get a line in Python在 Python 中搜索并获取一行
【发布时间】:2011-02-03 05:00:29
【问题描述】:

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

例如:

string = 
    qwertyuiop
    asdfghjkl

    zxcvbnm
    token qwerty

    asdfghjklñ

retrieve_line("token") = "token qwerty"

【问题讨论】:

    标签: python string search line


    【解决方案1】:

    你提到了“整行”,所以我假设 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
    

    【讨论】:

      【解决方案2】:

      如果您更喜欢单线:

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

      【讨论】:

        【解决方案3】:
        items=re.findall("token.*$",s,re.MULTILINE)
        >>> for x in items:
        

        如果token前还有其他字符也可以获取该行

        items=re.findall("^.*token.*$",s,re.MULTILINE)
        

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

        s='''
        qwertyuiop
        asdfghjkl
        
        zxcvbnm
        token qwerty
        
        asdfghjklñ
        '''
        

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

        ....
        ....
        token qwerty
        

        【讨论】:

          【解决方案4】:

          使用正则表达式

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

          【讨论】:

            猜你喜欢
            • 2022-06-19
            • 2011-12-28
            • 1970-01-01
            • 2011-12-17
            • 1970-01-01
            • 2017-12-19
            • 2014-02-14
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多