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

标签 python regex

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

  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 是您要查找的字符串。

关于python - 如何找到选择整行以仅从 Python 中的行中查找子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6419711/

相关文章:

python - sklearn LogisticRegressionCV 是否将所有数据用于最终模型

python - Pandas 中基于规则的列重命名

python - 使用 SQLAlchemy 和多处理卡在 Python 脚本中

c# - 使用 RegEx 对字符串进行大写和小写

javascript - 使用正则表达式获取不在特定html标签中的字符串

python - 使用 Python 批量运行 autoLISP

python - python中使用select从多个连接接收数据

javascript - jQuery Select 的转义括号

正则表达式只保留标签之间的内容但选择所有内容

regex - 模式匹配并使用 sed 在文本文件中的行尾或行首添加行