2

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.

3 Answers 3

8

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'
Sign up to request clarification or add additional context in comments.

4 Comments

os.path.dirname is the way to go as it is platform agnostic
@Samwise : One litte tweak if I want to replace the last part with some other string , how it can be done in above , like output should be '/d/d1/Projects/Alpha/workspace' , here test was replaced with workspace ?
@DeepSpace I agree that give a file path dirname is the best way to get the directory name, but OP asked about strings in general and gave a file path as an example, which is different from asking about file paths. :) It might be that this isn't actually a local file path, in which case os.path might not do the right thing.
@Bokambo Could do String.rpartition("/")[0] + "/workspace" -- or again, if we're allowed to assume that this is a local file path, do os.path.join(os.path.dirname(String), "workspace")
2

Use str.rfind function:

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

/d/d1/Projects/Alpha

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.