Skip to main content
 首页 » 编程设计

python之如何找到选择整行以仅从 Python 中的行中查找子字符串

2025年05月04日20kevingrace

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

  1. Tom is a guy
  2. Sara is a woman
  3. Alex is a guy too

我想搜索“Sara”,但想返回整个点赞

   def findLine(self, str): 
   ... 

当我调用 findLine("Sara") 时,它返回 "2. Sara is a woman"

如何使用 Python 和正则表达式(或其他非正则表达式方法)完成此操作

请您参考如下方法:

我将 str 重命名为 content see senderle's comment

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 

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

def findLine(self, str, search_str): 
    return [x for x in str.splitlines() if search_str in x] 

search_str 是您要查找的字符串。