I am trying to print the last part of a string before a certain character.
I'm not quite sure whether to use the string .split() method or string slicing or maybe something else.
Here is some code that doesn't work but I think shows the logic:
x = 'http://test.com/lalala-134'
print x['-':0] # beginning at the end of the string, return everything before '-'
Note that the number at the end will vary in size so I can't set an exact count from the end of the string.
You are looking for
str.rsplit()
, with a limit:.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:For splitting just once,
str.rpartition()
is the faster method as well; if you need to split more than once you can only usestr.rsplit()
.Demo:
and the same with
str.rpartition()
Difference between split and partition is split returns the list without delimiter and will split where ever it gets delimiter in string i.e.
and partition will divide the string with only first delimiter and will only return 3 values in list
so as you want last value you can use rpartition it works in same way but it will find delimiter from end of string