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)
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
输出:
具有
re.search()
函数的单行解决方案:输出:
您需要将字符串按行拆分,并在每行中搜索所需的单词。你知道吗
只要多行字符串在包含文本的最后一行之后的下一行结束,就不会超出列表的界限。如果您在前一行中有最后一个
"""
,则必须进行范围检查。你知道吗编辑:重读问题。找到论坛这个词后,你想要所有的行吗?我前面的例子只是让你看到下一行。对于找到关键字后的所有行,请使用以下命令:
len(s-1)
部分是可选的。取决于结果中是否包含尾随空行。如果你想要最后一个空行,只要把它改回len(s)
。你知道吗相关问题 更多 >
编程相关推荐