Skip to content
Related Articles

Related Articles

Python | Split on last occurrence of delimiter

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 25 Jun, 2022

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

Output : 

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

Output : 

The original string : gfg, is, good, better, and best
The splitted list at the last comma : ('gfg, is, good, better', ', ', 'and best')

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

Output

The original string : gfg, is, good, better, and best
The splitted list at the last comma : ['gfg, is, good, better', ' and best']

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!