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

merge strings lying between two specific values

I want to merge all the strings present in the list into single string, if they lie between ‘zz’ using python

old_list = ['1', 'zz', '1', '2', 'zz', '1', '1', '1', 'zz', '1', 'zz']

Expected output:

new_list = ['1', '11', '111', '1']

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

>Solution :

Solution with itertools.groupby:

from itertools import groupby


old_list = ["1", "zz", "1", "1", "zz", "1", "1", "1", "zz", "1", "zz"]

new_list = []
for k, g in groupby(old_list, lambda k: k == "zz"):
    if not k:
        new_list.append("".join(g))

print(new_list)

Prints:

['1', '11', '111', '1']
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