Neverland
Neverland

Reputation: 775

Reduce strings in python to a specific point

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!

Upvotes: 1

Views: 1991

Answers (7)

tzot
tzot

Reputation: 95961

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.

Upvotes: 0

wisty
wisty

Reputation: 7061

'/'.join(s.split('/')[:-1]+[''])

Upvotes: 0

SilentGhost
SilentGhost

Reputation: 319621

>>> os.path.split('how/to/implement/this'.rstrip('/'))
('how/to/implement', 'this')
>>> os.path.split('how/to/implement/this/'.rstrip('/'))
('how/to/implement', 'this')

Upvotes: 0

ghostdog74
ghostdog74

Reputation: 342433

>>> import os
>>> path="how/to/implement/this"
>>> os.path.split(path)
('how/to/implement', 'this')
>>> os.path.split(path)[0]
'how/to/implement'

Upvotes: 1

Grant Paul
Grant Paul

Reputation: 5902

 newString = oldString[:oldString[:-1].rfind('/')]
 # strip out trailing slash    ----^       ^---- find last remaining slash

Upvotes: 5

Greg Hewgill
Greg Hewgill

Reputation: 993303

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'

Upvotes: 6

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798746

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

Upvotes: 5

Related Questions