Reputation: 41
I have a input text file:
This file contains information of students who are joining picnic:
@@@ bob alice rhea john
mary alex roma
peter &##&
Now I would like to append students name in a list in a line when find @@@ marker & stop appending when find &##& marker. Output should be(using python):
bob alice rhea john mary alex roma peter
Upvotes: 1
Views: 183
Reputation: 640
You can use this method
txt = """This file contains information of students who are joining picnic:
@@@ bob alice rhea john
mary alex roma
peter &##&"""
or :
txt = open("./file.txt").read()
ls = txt.split("@@@")[1].split("&##&")[0].split()
print(ls)
This prints :
['bob', 'alice', 'rhea', 'john', 'mary', 'alex', 'roma', 'peter']
Upvotes: 1
Reputation: 520878
Using re.findall
with re.sub
:
inp = """This file contains information of students who are joining picnic:
@@@ bob alice rhea john
mary alex roma
peter &##&"""
output = re.sub(r'\s+', ' ', re.findall(r'@@@\s+(.*?)\s+&##&', inp, flags=re.DOTALL)[0])
print(output) # bob alice rhea john mary alex roma peter
If you want a list, then use:
output = re.split(r'\s+', re.findall(r'@@@\s+(.*?)\s+&##&', inp, flags=re.DOTALL)[0])
print(output)
This prints:
['bob', 'alice', 'rhea', 'john', 'mary', 'alex', 'roma', 'peter']
Upvotes: 1