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

How to split a string into list of combinations

Given a string like /root/2/1/2, how do we construct the following list:

['/root/2/1/2', 'root/2/1', 'root/2', '/root']

>Solution :

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

A very simple implementation is to split once from the right side on / character iteratively until there is nothing left.

left = '/root/2/1/2'
lst = []
while left:
    lst.append(left)
    left, right = left.rsplit('/', 1)

print(lst)   # ['/root/2/1/2', '/root/2/1', '/root/2', '/root']

Using the walrus operator, we can also write it in a single line (much less readable than the while loop though):

left = '/root/2/1/2'
lst = [left, *(left for _ in range(left.count('/')) if (left:=left.rsplit('/', 1)[0]))]
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