'join list elements between two elements in a list

I have a list and I have the two list elements start:and end:. Between these two there is an undefined number of elements that I would like to join to the start element. Also, end: can have different names but it always starts with end:. This is my list

sth_list = ['name: michael', 'age:56', 'start:','','something','is','happening','end:', 'anything could be here:', 'some other things:', 'more things:'] 

and I would like to get this

 ['name: michael', 'age:56', 'start: something is happening', 'end:', 'anything could be here:', 'some other things:', 'more things:']

what I have so far is this. But it only gives me the joined elements between start and end but I would like to have the full list as above.

 ''.join([element for n, element in enumerate(sth_list) if ((n>sth_list.index("start:")) & (n<sth_list.index([e for e in sth_list if e.startswith('end')][0])))])


Solution 1:[1]

You can use a classical loop:

import re

out = []
flag = False
for item in sth_list:
    if item.startswith('end:'):
        flag = False
    if flag:
        if item:
            out[-1] += ' '+item
    else:
        out.append(item)
    if item == 'start:':
        flag = True

output:

['name: michael',
 'age:56',
 'start: something is happening',
 'end:',
 'anything could be here:',
 'some other things:',
 'more things:']

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1