views:

111

answers:

7

I have strings in my python application that look this way:

test1/test2/foo/

Everytime I get such a string, I want to reduce it, beginning from the tail and reduced until the fist "/" is reached.

test1/test2/

More examples:

foo/foo/foo/foo/foo/  => foo/foo/foo/foo/
test/test/            => test/
how/to/implement/this => how/to/implement/

How can I implement this in python?

Thanks in advance!

+5  A: 

str.rsplit() with the maxsplit argument. Or if this is a path, look in os.path or urlparse.

Ignacio Vazquez-Abrams
+5  A: 
 newString = oldString[:oldString[:-1].rfind('/')]
 # strip out trailing slash    ----^       ^---- find last remaining slash
chpwn
Alternatively you can use `.rfind('/', 0, -2)`.
KennyTM
Great! Thanks a lot!!!
Neverland
this is really is one of the poorest answers.
SilentGhost
I agree with SilentGhost, this really is one of the worst alternatives. The os.path based answers are much better.
fuzzy lollipop
Well, I had no idea it was for paths!
chpwn
This solution is best for me. Thanks!
Neverland
+6  A: 

It sounds like the os.path.dirname function might be what you're looking for. You may need to call it more than once:

>>> import os.path
>>> os.path.dirname("test1/test2/")
'test1/test2'
>>> os.path.dirname("test1/test2")
'test1'
Greg Hewgill
`dirname` is useful in general, but in this case the user wants `test2` to be removed on both cases.
Nick D
+1  A: 
>>> import os
>>> path="how/to/implement/this"
>>> os.path.split(path)
('how/to/implement', 'this')
>>> os.path.split(path)[0]
'how/to/implement'
ghostdog74
This works only for this specific example (string). But it is not a generic solution.
Neverland
what are the string examples that breaks when this method is used?
ghostdog74
A: 
>>> os.path.split('how/to/implement/this'.rstrip('/'))
('how/to/implement', 'this')
>>> os.path.split('how/to/implement/this/'.rstrip('/'))
('how/to/implement', 'this')
SilentGhost
A: 
'/'.join(s.split('/')[:-1]+[''])
wisty
There are approximately half a dozen techniques that are better than this.
Ignacio Vazquez-Abrams
A: 

If you mean "/" as in path separator, the function you want is:

os.path.dirname(your_argument)

If not, then you want:

def your_function(your_argument):
    result= your_argument.rstrip("/").rpartition("/")[0]
    if result:
        return result + "/"
    return result

Please specify what should be the result when "test/" is used as an argument: should it be "/" or ""? I assumed the second in my code above.

ΤΖΩΤΖΙΟΥ
"/" is the path separator.
Neverland