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
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
Try this:
In [6]: a = "[email protected]:/home/hello/there"
In [7]: a.rpartition('/')[0]
Out[7]: '[email protected]:/home/hello'
>>> "[email protected]:/home/hello/there".rsplit('/', 1)
['[email protected]:/home/hello', 'there']
>>> "[email protected]:/home/hello/there".rsplit('/', 1)[0]
'[email protected]:/home/hello'
you can try this
a = "[email protected]:/home/hello/there"
print '/'.join(a.split('/')[:-1])
Have you considered os.path.dirname ?
>>> a = "[email protected]:/home/hello/there"
>>> import os
>>> os.path.dirname(a)
'[email protected]:/home/hello'
a = "[email protected]:/home/hello/there" a.rsplit('/', 1)[0]
Result - [email protected]:/home/hello/
Simpler way:
a = "[email protected]:/home/hello/there"
a = a.split("/")[:-1].join("/")
print(a)
os.path.split, etc.) rather than string manipulation.