The splitting of strings has always been discussed in various applications and use cases. One of the interesting variations of list splitting can be splitting the list on delimiter but this time only on the last occurrence of it. Let’s discuss certain ways in which this can be done.
Method #1: Using rsplit(str, 1) The normal string split can perform the split from the front, but Python also offers another method that can perform this very task from the rear end, hence increasing the versatility of applications.
Python3
# Python3 code to demonstrate # Split on last occurrence of delimiter # using rsplit() # initializing string test_string = "gfg, is, good, better, and best" # printing original string print ( "The original string : " + str (test_string)) # using rsplit() # Split on last occurrence of delimiter res = test_string.rsplit( ', ' , 1 ) # print result print ( "The splitted list at the last comma : " + str (res)) |
The original string : gfg, is, good, better, and best The splitted list at the last comma : ['gfg, is, good, better', 'and best']
Method #2: Using rpartition() This function can also perform the desired reverse partition, but the drawbacks to using this is the construction of additional delimiter value and also the speed is slower than the above method and hence not recommended.
Python3
# Python3 code to demonstrate # Split on last occurrence of delimiter # using rpartition() # initializing string test_string = "gfg, is, good, better, and best" # printing original string print ( "The original string : " + str (test_string)) # using rpartition() # Split on last occurrence of delimiter res = test_string.rpartition( ', ' ) # print result print ( "The splitted list at the last comma : " + str (res)) |
The original string : gfg, is, good, better, and best The splitted list at the last comma : ('gfg, is, good, better', ', ', 'and best')
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3 : Using split() and replace() methods.
Python3
# Python3 code to demonstrate # Split on last occurrence of delimiter # initializing string test_string = "gfg, is, good, better, and best" # printing original string print ( "The original string : " + str (test_string)) # Split on last occurrence of delimiter p = test_string.count( "," ) c = 0 new = "" for i in test_string: if (i = = "," and c < p - 1 ): new + = "*" c + = 1 else : new + = i x = new.split( "," ) x[ 0 ] = x[ 0 ].replace( "*" , "," ) # print result print ( "The splitted list at the last comma : " + str (x)) |
The original string : gfg, is, good, better, and best The splitted list at the last comma : ['gfg, is, good, better', ' and best']
Method #4: Using rfind() and slicing
- Initialize the test string and the delimiter.
- Find the index of the last occurrence of the delimiter in the test string using rfind().
- If the delimiter is found, split the test string into two parts using slicing, where the first part is the substring before the delimiter and the second part is the substring after the delimiter. Otherwise, return the test string as a list with a single element.
- Return the result.
Python3
# Python3 code to demonstrate # Split on last occurrence of delimiter # using rfind() and slicing # initializing string test_string = "gfg, is, good, better, and best" # printing original string print ( "The original string : " + str (test_string)) # using rfind() and slicing # Split on last occurrence of delimiter delimiter = ', ' index = test_string.rfind(delimiter) if index ! = - 1 : res = [test_string[:index], test_string[index + len (delimiter):]] else : res = [test_string] # print result print ( "The splitted list at the last comma : " + str (res)) # This code is contributed by Vinay Pinjala. |
The original string : gfg, is, good, better, and best The splitted list at the last comma : ['gfg, is, good, better', 'and best']
Time Complexity: O(n), where n is the length of the test string, because the rfind() method iterates over the characters of the string once to find the index of the last occurrence of the delimiter, and the slicing operation takes constant time.
Auxiliary Space: O(n), because we are storing the test string and the result list in memory. However, the slicing operation creates a new string in memory, which takes additional space proportional to the length of the second part of the string (i.e., after the delimiter).
Method #5: Using rsplit() with maxsplit parameter
Python3
# Python3 code to demonstrate # Split on last occurrence of delimiter # using rsplit() with maxsplit parameter # initializing string test_string = "gfg, is, good, better, and best" # printing original string print ( "The original string : " + str (test_string)) # using rsplit() with maxsplit parameter # Split on last occurrence of delimiter delimiter = ', ' res = test_string.rsplit(delimiter, 1 ) # print result print ( "The splitted list at the last comma : " + str (res)) |
The original string : gfg, is, good, better, and best The splitted list at the last comma : ['gfg, is, good, better', 'and best']
Time Complexity: O(n), where n is the length of the input string.
Auxiliary Space: O(1), as we are not using any extra data structure or list to store the output.
Method #6: Using the rindex() method and slicing:
Algorithm:
- Initialize the input string.
- Use rindex() method to get the last index of the delimiter.
- Split the input string using slicing operator.
- Return the split string as list.
Python3
# initializing string test_string = "gfg, is, good, better, and best" # printing original string print ( "The original string : " + str (test_string)) res = [test_string[:test_string.rindex( ', ' )], test_string[test_string.rindex( ', ' ) + 2 :]] # print result print ( "The splitted list at the last comma : " + str (res)) #This code is contributed by Jyothi pinjala. |
The original string : gfg, is, good, better, and best The splitted list at the last comma : ['gfg, is, good, better', 'and best']
Time complexity: O(1) – The time complexity of this code is constant, because we’re only performing a small number of operations on a fixed-size input.
Auxiliary Space : O(1) – The space complexity of this code is also constant, as we’re only creating a few variables that store a small amount of data.
Method #7: using numpy:
- Import the numpy module and define a string test_string.
- Print the original string.
- Use the np.char.rpartition() function to split the string at the last occurrence of the delimiter “, “.
- The function returns a tuple of three elements:
- The first element contains the part of the string before the last occurrence of the delimiter.
- The second element contains the last occurrence of the delimiter itself.
- The third element contains the part of the string after the last occurrence of the delimiter.
- Extract the first, second, and third elements of the returned tuple to get the desired result.
Python3
import numpy as np test_string = "gfg, is, good, better, and best" print ( "The original string : " + str (test_string)) res = np.char.rpartition(test_string, ', ' ) res = res[ 0 ], res[ 1 ], test_string.split( ', ' )[ - 1 ] print ( "The splitted list at the last comma : " + str (res)) # This code is contributed by Rayudu. |
Output: The original string : gfg, is, good, better, and best The splitted list at the last comma : ('gfg, is, good, better', ', ', 'and best')
Time complexity: O(n), where n is the length of the string, because the function iterates through each character of the string once. The time complexity of the remaining operations is O(1). Therefore, the overall time complexity of the code is O(n).
Auxiliary Space: O(n), because the returned tuple contains three new strings, each of which can potentially be as long as the input string. However, in practice, the returned strings are likely to be smaller than the input string since they contain only a portion of the original string.