Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split string in to 2 based on last occurrence of a separator

Tags:

python

string

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.

like image 407
Yashwanth Kumar Avatar asked Sep 08 '11 16:09

Yashwanth Kumar


People also ask

How do I split the last index of a string?

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);

How do you split a string at the last delimiter in Python?

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.

How do you get the last split in Python?

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 .


1 Answers

Use rpartition(s). It does exactly that.

You can also use rsplit(s, 1).

like image 185
Petar Ivanov Avatar answered Sep 23 '22 08:09

Petar Ivanov