Split a string on last occurrence of delimiter or separator in Python

Splitting of the string is a process in which the whole string is broken down into parts. It may have many uses in programming while making software. But here we will split a string on the last occurrence of delimiter or separator in Python.

So hello guys, in this post we will learn to split a string on the last occurrence of delimiter or separator in Python.

Delimiter: A character that separates the words in a string. For example, comma(,).

Also read: Keyword-Only Arguments in Python

Python provides a method that split the string from rear end of the string. The inbuilt Python function rsplit() that split the string on the last occurrence of the delimiter.

Syntax:

rsplit("delimiter",1)

In rsplit() function 1 is passed with the argument so it breaks the string only taking one delimiter from last. If the string has more than one delimiter and 2 is passed in place of 1 the function split the string from second last delimiter and last delimiter both.

line1= "Thank you, have a nice day, Regards XYZ"
print("Before Splitting:",line1)

#using rsplit function
res=line1.rsplit(',',1)
print(res)

Output:

Before Splitting: Thank you, have a nice day, Regards XYZ 
['Thank you, have a nice day', ' Regards XYZ ']

There is also another function in Python that can split the string from the rear end. It also shows the delimiter separately from where it split the string.

Syntax:

rpartition("delimiter")
line1= "Thank you, have a nice day, Regards XYZ "
print("Before Splitting:",line1)

# using rpartition function
result=line1.rpartition(",")
print(result)

Output:

Before Splitting: Thank you, have a nice day, Regards XYZ 
('Thank you, have a nice day', ',', ' Regards XYZ ')

I hope you understood the tutorial. If you have any queries or doubts related to this topic please comment below.

Also read: How to read an image from URL in Python

Thank You

 

Leave a Reply

Your email address will not be published. Required fields are marked *