在python中提取所有行,包括包含子字符串的行和子字符串后面的行

2024-05-13 22:14:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到了这样的问题:在包含子字符串所在的行之后,我试图提取行。你知道吗

s="""
   This is so awesome
   I need to do this more often
   This forum rocks
   Help me
  """

如果我搜索的子字符串是论坛,我想得到如下结果

   this forum rocks
   Help me

我试着用下面的语句

s.lower().split("forum",1)[1]

我的输出是

forum rocks

感谢您的帮助。你知道吗


Tags: to字符串soismorehelpforumneed
3条回答
l = s.split('\n')
for n, str in enumerate(l):
    if 'forum' in str:
        print ('\n'.join(l[n:]))
        break

输出:

   This forum rocks
   Help me

具有re.search()函数的单行解决方案:

import re

s="""
   This is so awesome
   I need to do this more often
   This forum rocks
   Help me
  """    
result = re.search(r'.*\bforum[\s\S]*', s, re.M).group()
print(result)

输出:

   This forum rocks
   Help me

您需要将字符串按行拆分,并在每行中搜索所需的单词。你知道吗

s="""
This is so awesome
I need to do this more often
This forum rocks
Help me
""".split('\n')
for line in range(len(s)):
    if "forum" in s[line]:
        print(s[line])
        print(s[line+1])

只要多行字符串在包含文本的最后一行之后的下一行结束,就不会超出列表的界限。如果您在前一行中有最后一个""",则必须进行范围检查。你知道吗

编辑:重读问题。找到论坛这个词后,你想要所有的行吗?我前面的例子只是让你看到下一行。对于找到关键字后的所有行,请使用以下命令:

s="""
This is so awesome
I need to do this more often
This forum rocks
Help me
""".split('\n')
found = False
for line in range(len(s-1)):
    if "forum" in s[line] or found:
        print(s[line])
        found = True

len(s-1)部分是可选的。取决于结果中是否包含尾随空行。如果你想要最后一个空行,只要把它改回len(s)。你知道吗

相关问题 更多 >