您正在尋找str.rsplit()
,有限制:
print x.rsplit('-', 1)[0]
.rsplit()
搜索從輸入字符串的結束分裂字符串,第二個參數的限制多少次,它會分裂,只有一次。
另一種選擇是使用str.rpartition()
,這將只拆分只是一次:
print x.rpartition('-')[0]
分裂只需一次,str.rpartition()
是更快的方法爲好;如果您需要分割不止一次,則只能使用str.rsplit()
。
演示:
>>> x = 'http://test.com/lalala-134'
>>> print x.rsplit('-', 1)[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rsplit('-', 1)[0]
'something-with-a-lot-of'
與str.rpartition()
>>> print x.rpartition('-')[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rpartition('-')[0]
'something-with-a-lot-of'
非常感謝你,我用'打印x.rsplit(「 - 」,1)[1]'和它的工作,謝謝。我也剛剛遇到'print x.rpartition(' - ')[2]',這似乎也起作用!再次感謝! – user1063287 2013-04-06 13:52:41
沒錯,你的措辭有點模棱兩可;你在**某個字符之前*要求*字符串的最後部分*;我想,你的意思是。 :-) – 2013-04-06 13:53:51
但我的精彩評論! '從字符串的末尾開始',我明白你的意思是哈哈。 – user1063287 2013-04-06 14:08:00