You are looking for str.rsplit()
, with a limit:
print x.rsplit('-', 1)[0]
.rsplit()
searches for the splitting string from the end of input string, and the second argument limits how many times it'll split to just once.
Another option is to use str.rpartition()
, which will only ever split just once:
print x.rpartition('-')[0]
For splitting just once, str.rpartition()
is the faster method as well; if you need to split more than once you can only use str.rsplit()
.
Demo:
>>> 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'
and the same with str.rpartition()
>>> print x.rpartition('-')[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rpartition('-')[0]
'something-with-a-lot-of'