如何找到选择整行来查找Python中的行中的子串

1 python regex

例如,我在文件中有以下几行:

  1. 汤姆是个男人
  2. 莎拉是个女人
  3. 亚历克斯也是一个人

我想搜索"Sara"但想要回归整体

   def findLine(self, str):
   ...
Run Code Online (Sandbox Code Playgroud)

当我打电话时findLine("Sara"),它会返回"2. Sara is a woman"

如何使用Python和正则表达式(或其他非正则表达式方法)实现此目的

GWW*_*GWW 5

我重命名strcontent看发送者的评论

def findLine(self, content, search_str):
    for line in content.splitlines()
        if search_str in line:
            return line
    #or something else because the search_str was not found
    return None
Run Code Online (Sandbox Code Playgroud)

或者如果你想要一个包含sarah的所有行的列表

def findLine(self, str, search_str):
    return [x for x in str.splitlines() if search_str in x]
Run Code Online (Sandbox Code Playgroud)

search_str 是你想要找到的字符串.

  • 最好不要使用`str`作为[metasyntactic变量](http://en.wikipedia.org/wiki/Metasyntactic_variable),因为它掩盖了内置的字面意思. (2认同)