Bokambo
Bokambo

Reputation: 4480

Python Get complete string before last slash

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.

Upvotes: 2

Views: 1237

Answers (3)

Willy Lutz
Willy Lutz

Reputation: 314

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

Upvotes: 2

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Use str.rfind function:

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

/d/d1/Projects/Alpha

Upvotes: 2

Samwise
Samwise

Reputation: 71464

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'

Upvotes: 8

Related Questions