Skip to content Skip to sidebar Skip to footer

Split String In To 2 Based On Last Occurrence Of A Separator

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,

Solution 1:

Use rpartition(s). It does exactly that.

You can also use rsplit(s, 1).

Solution 2:

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

Solution 3:

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']

Post a Comment for "Split String In To 2 Based On Last Occurrence Of A Separator"