Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Split text By specific keyword

I have a list and I want to add the words that come after a certain word in this list into a new list.

exp input

list =["split","foo","foo","foo","split","mama","mama","split","orange","melon"]

exp output

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

list =["split","foo","foo","foo"]
      ["split","mama", "mama"   ]
      ["split","orange","melon" ]

I encountered a logical error, I checked each child of the list and tried to throw the objects up to the next argument into a new list.


for i in liste:
    if i.lower() == "split":
        x = True
    if x:
        new_list.append(i)

I don’t know what to do after the first loop. How can I reset the bool value and create a new list?

>Solution :

You can simply iterate and keep a track of the current visisted set.

l =["split","foo","foo","foo","split","mama","mama","split","orange","melon"]
ans = []
curr = []
split_word = "split"
for i in l:
    if i != split_word:
        curr.append(i)
    else:
        if curr:
            ans.append(curr)
        curr = [i]
if curr:
    ans.append(curr)

print(ans)
# [['split', 'foo', 'foo', 'foo'], ['split', 'mama', 'mama'], ['split', 'orange', 'melon']]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading