Python Get complete string before last slash

Question:

I want to get complete string path before last occurrence of slash (/)

String : /d/d1/Projects/Alpha/tests
Output : /d/d1/Projects/Alpha

I am able to get the last part of string after last slash by doing

String.split('/')[-1]

But I want to get "/d/d1/Projects/Alpha"

Thanks.

Asked By: Bokambo

||

Answers:

The simplest option is str.rpartition, which will give you a 3-tuple of the string before, including, and after the rightmost occurrence of a given separator:

>>> String = "/d/d1/Projects/Alpha/tests"
>>> String.rpartition("/")[0]
'/d/d1/Projects/Alpha'

For the specific case of finding the directory name given a file path (which is what this looks like), you might also like os.path.dirname:

>>> import os.path
>>> os.path.dirname(String)
'/d/d1/Projects/Alpha'
Answered By: Samwise

Use str.rfind function:

s = '/d/d1/Projects/Alpha/tests'
print(s[:s.rfind('/')])

/d/d1/Projects/Alpha
Answered By: RomanPerekhrest

Two easy methods:
Using split
as you did, you can use split method, then use join, as following, it should work:

in_str = "/d/d1/Projects/Alpha/tests"
out_str = '/'.join(in_str.split('/')[:-1]) # Joining all elements except the last one

Or
Using os.path.dirname (would recommend, cleaner)

in_str = "/d/d1/Projects/Alpha/tests"
out_str = os.path.dirname(in_str)

Both give the awaited result

Answered By: Willy Lutz
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.