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 on second last slash?

I want to split a string on the second last slash,

so if I have a string like /tmp/fold/merge/annots I want to get /tmp/fold/ and merge/annots returned.

Same if I have /tmp/long/dir/fold/merge/annots I want to get /tmp/long/dir/fold/ and merge/annots

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

What’s the best way to do this? I’ve tried rsplit and split a few times but not getting what I want

>Solution :

String splitting works, but I would actually use pathlib for this.

import pathlib

p = pathlib.Path('/tmp/long/dir/fold/merge/annots')
p.parts[-2:]
# ('merge', 'annots')

If you need it as a path object,

result = pathlib.Path(*p.parts[-2:])

which can be converted directly to string if you need to use it that way specifically.

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