I would like to know if there is any built in function in python to break the string in to 2 parts, based on the last occurrence of a separator.
for eg: consider the string "a b c,d,e,f" , after the split over separator ",", i want the output as
"a b c,d,e" and "f".
I know how to manipulate the string to get the desired output, but i want to know if there is any in built function in python.
You can use lastIndexOf on String which returns you the index of the last occurrence of a chain of caracters. String thing = "132131_12313_1321_312"; int index = thing. lastIndexOf("_"); String yourCuttedString = thing. substring(0, index);
Python provides a method that split the string from rear end of the string. The inbuilt Python function rsplit() that split the string on the last occurrence of the delimiter. In rsplit() function 1 is passed with the argument so it breaks the string only taking one delimiter from last.
Use the str. rsplit() method with maxsplit set to 1 to split a string and get the last element. The rsplit() method splits from the right and will only perform a single split when maxsplit is set to 1 .
Use rpartition(s)
. It does exactly that.
You can also use rsplit(s, 1)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With