例如,我在文件中有以下几行:
- Tom is a guy
- Sara is a woman
- 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 是您要查找的字符串。
