如何在Python中删除字符串中的最后一个单词?

时间:2012-12-10 05:05:43

标签: python string

例如,如果我有这样的字符串:

a = "username@102.1.1.2:/home/hello/there"

如何删除上一个/后的最后一个单词。结果应该是这样的:

username@102.1.1.2:/home/hello/ 

OR 

username@102.1.1.2:/home/hello

6 个答案:

答案 0 :(得分:7)

试试这个:

In [6]: a = "username@102.1.1.2:/home/hello/there"

In [7]: a.rpartition('/')[0]
Out[7]: 'username@102.1.1.2:/home/hello'

答案 1 :(得分:3)

>>> "username@102.1.1.2:/home/hello/there".rsplit('/', 1)
['username@102.1.1.2:/home/hello', 'there']
>>> "username@102.1.1.2:/home/hello/there".rsplit('/', 1)[0]
'username@102.1.1.2:/home/hello'

答案 2 :(得分:2)

你可以试试这个

a = "username@102.1.1.2:/home/hello/there"
print '/'.join(a.split('/')[:-1])

答案 3 :(得分:1)

这可能不是最蟒蛇的方式,但我相信以下方法可行。

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

答案 4 :(得分:0)

您考虑过os.path.dirname吗?

>>> a = "username@102.1.1.2:/home/hello/there"
>>> import os
>>> os.path.dirname(a)
'username@102.1.1.2:/home/hello'

答案 5 :(得分:0)

a =“username@102.1.1.2:/ home / hello / there” a.rsplit('/',1)[0]

结果 - username@102.1.1.2:/home/hello/