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
What's the best way to do this? I've tried rsplit
and split
a few times but not getting what I want
CodePudding user response:
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.
CodePudding user response:
like this?
l = '/tmp/fold/merge/annots'
latter = l.split('/',3)[-1]
former = l.replace(latter,'')
print(former)
CodePudding user response:
To split a string on the penultimate bar, try writing like this:
import pathlib
x = pathlib.Path('/tmp/long/dir/fold/merge/annots')
x.parts[-2:]