0

For example if I have a string like this:

a = "[email protected]:/home/hello/there"

How do I remove the last word after the last /. The result should be like this:

[email protected]:/home/hello/ 

OR 

[email protected]:/home/hello
2
  • Since this appears to be a path/url/similar kind of thing, you may want to use an appropriate function (os.path.split, etc.) rather than string manipulation. Commented Dec 10, 2012 at 5:25
  • You are right. I am looking into os.path.split too. Thanks for the heads up. Commented Dec 10, 2012 at 5:43

7 Answers 7

7

Try this:

In [6]: a = "[email protected]:/home/hello/there"

In [7]: a.rpartition('/')[0]
Out[7]: '[email protected]:/home/hello'
Sign up to request clarification or add additional context in comments.

Comments

3
>>> "[email protected]:/home/hello/there".rsplit('/', 1)
['[email protected]:/home/hello', 'there']
>>> "[email protected]:/home/hello/there".rsplit('/', 1)[0]
'[email protected]:/home/hello'

Comments

2

you can try this

a = "[email protected]:/home/hello/there"
print '/'.join(a.split('/')[:-1])

1 Comment

The join is unnecessary and ugly. Using rsplit() is smarter!
1

This may not be the most pythonic way but I believe the following would work.

tokens=a.split('/')
'/'.join(tokens[:-1])

1 Comment

The join is unnecessary and ugly. Using rsplit() is smarter!
0

Have you considered os.path.dirname ?

>>> a = "[email protected]:/home/hello/there"
>>> import os
>>> os.path.dirname(a)
'[email protected]:/home/hello'

Comments

0

a = "[email protected]:/home/hello/there" a.rsplit('/', 1)[0]

Result - [email protected]:/home/hello/

Comments

0

Simpler way:

a = "[email protected]:/home/hello/there"
a = a.split("/")[:-1].join("/")
print(a)

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.