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

PythonString

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

Use rpartition(s). It does exactly that.

You can also use rsplit(s, 1).

Solution 2 - Python

>>> "a b c,d,e,f".rsplit(',',1)
['a b c,d,e', 'f']

Solution 3 - Python

You can split a string by the last occurrence of a separator with rsplit:

> Returns a list of the words in the string, separated by the delimiter string (starting from right).

To split by the last comma:

>>> "a b c,d,e,f".rsplit(',', 1)
['a b c,d,e', 'f']

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYashwanth KumarView Question on Stackoverflow
Solution 1 - PythonPetar IvanovView Answer on Stackoverflow
Solution 2 - PythonGryphiusView Answer on Stackoverflow
Solution 3 - PythonwRARView Answer on Stackoverflow