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

如何在Python中删除字符串中的最后一个单词?,python,string,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 如何删除最后一个/后面的最后一个单词。结果应该是这样的: a = "username@102.1.1.2:/home/hello/there" username@102.1.1.2:/home/hello/ OR usernam

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

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

OR 

username@102.1.1.2:/home/hello
如何删除最后一个
/
后面的最后一个单词。结果应该是这样的:

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

OR 

username@102.1.1.2:/home/hello
你可以试试这个

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

这可能不是最具Python风格的方式,但我相信以下方法会奏效

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

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'
你考虑过吗

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


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

该连接是不必要的,而且很难看。使用rsplit()更聪明!连接是不必要的,也是丑陋的。使用rsplit()更聪明!由于这似乎是一个路径/url/类似的类型,您可能希望使用适当的函数(
os.path.split
,等等)而不是字符串操作。您是对的。我也在研究os.path.split。谢谢你的提醒。