Reputation: 511
I am running into problems where I am trying to extract the lines after including the line from where the substring exist.
s="""
This is so awesome
I need to do this more often
This forum rocks
Help me
"""
If the substring I search is forum, I want to get the result as
this forum rocks
Help me
I tried using the following statement
s.lower().split("forum",1)[1]
and my output is
forum rocks
Any help is appreciated.
Upvotes: 1
Views: 870
Reputation: 4417
Try this, It will work for a string containing any number of lines.
s="""
This is so awesome
I need to do this more often
This forum rocks
Help me
"""
s=s.split('\n')
c=0
for i in s:
if i.find("forum")!=-1: # no match, find returns -1
print "\n".join(s[c:])
c+=1
Output :
This forum rocks
Help me
So, basically you find the index in the array where your match has been found and then return everything after that (by joining with a \n
as was the case in the original string).
Upvotes: 1
Reputation: 3547
l = s.split('\n')
for n, str in enumerate(l):
if 'forum' in str:
print ('\n'.join(l[n:]))
break
Output:
This forum rocks
Help me
Upvotes: 1
Reputation: 2524
You'll want to split the string by line, and search each line for the word you want.
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])
As long as the multi-line string ends on the next line after the last line with text in it, you won't go out of bounds for the list. If you have the last """
on the previous line, next to Help me
, you'll have to do a range check.
EDIT: Re-read the question. You want all lines after the word forum is found? The previous example I gave just gets you the next line. For all lines after the key word is found, use this:
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
The len(s-1)
part is optional. Depending on whether you want the trailing blank line included in the results. If you want that last blank line, just change it back to len(s)
.
Upvotes: 1
Reputation: 92904
One-line solution with re.search()
function:
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)
The output:
This forum rocks
Help me
Upvotes: 2