Fortunately, there exist functions that can split string on last occurrence of delimiter in Python. We’ll help you do this using two different functions. Each method is relatively easy, and can use whichever fits you most.
Split string on last occurrence of delimiter in Python
The rindex() function gives out the last occurrence of a substring found in a string. If no substring appears, it will raise an exception. Technically, it will search for the substring from the end to the beginning of a string, which is different from the function index():
str.rindex(str, begin, end)
- string: Required. This specifies the string to be searched.
- begin: The index to start searching. By default, it’s 0.
- end: This is the ending index; by default, it’s the length of the string.
string = 'This,is,Learn,Share,IT' index = string.rindex(',') string1 = string[0:index] string2 = string[index+1::] print (string1) print (string2)
The logic behind this method is very simple. We use the rindex() method to return the index of the last occurrence of the comma (our delimiter) and then split a string into two parts: the first part is from the beginning (index 0) to the index of the last comma, and the second part is from after the comma index to end of the original string.
The rsplit() method can split a string into an array by using a separator and searching from the end to the beginning of the string. This is different from the split() function, however, if you don’t declare the maxsplit parameter, then those two methods will produce the same results
- separator: The delimiter to split, by default it’s a whitespace.
- maxsplit: The maximum number of splits, by default, it’s -1, which means no limits.
string = 'This,is,Learn,Share,IT' splits = string.rsplit(',', 1) string1 = splits string2 = splits print (string1) print (string2)
You may be wondering why it returns an array containing two elements; this is because we have declared the maximum number of splits is 1, and 1 split will result in 2 elements. The rsplit() function will search the separator from the end to the beginning of the string, which is different from the split() function.
We have discovered some ways to split string on last occurrence of delimiter in Python. Although there are many ways to deal with this type of problem, we hope you can sort out the quickest way which suits you best. Thanks for reading!
Maybe you are interested:
- Convert a String to an Enum in Python
- Convert an Enum to a String in Python
- Ways To Split A String By Tab In Python
Name of the university: HCMUT