Python program to split a string on the last occurrence of the delimiter

In this tutorial, we will learn how to split a string on the last occurrence of the delimiter in Python. So, what is a delimiter?

A delimiter is a character that we use to define the boundary between
the given data streams. For example for the string text = “a,b,c,d,e” the delimiter is “, ” if we consider separating each character of the string.

splitting a string on the last occurrence of the delimiter

Let’s have a look to the code below

string = "Python-is-awesome-Its-easy-to-learn"
delimiter = "-"
print(string.rsplit(delimeter,maxsplit = 1))
Output::
['Python-is-awesome-Its-easy-to', 'learn']

Here since the delimiter is ‘-‘. So the string divides itself into 2 parts as maxsplit = 1, which describes the number of splits that should be made of the string using the delimiter. And returns a list with the separated strings. Now, We might wonder and question about the use of rsplit() instead of split(). The answer lies in the key difference between the two functions. According to the documentation we define split() and rsplit() as

  • S.split(…)Return a list of the words in S, using the delimiter string.
    If the delimiter is not specified or is None, any whitespace string is a
    separator and it removes empty strings from the result.
    Let us use split function where we used rsplit() for the above example

    string = "Python-is-awesome-Its-easy-to-learn"
    delimiter = "-"
    print(string.split(delimiter,maxsplit = 1))
    Output::
    ['Python', 'is-awesome-Its-easy-to-learn']

Here the function splits the string from the very first delimiter which makes it different from rsplit() function.

  • S.rsplit(…)

Return a list of the words in S, using the delimiter string, starting at the end of the string and working to the front which is described above and is the only difference that makes it
different from the split() function.

Hope this article helps you to understand how to split a string on the last occurrence of the delimiter in Python.

Interested readers may visit Python Documentations to enrich your knowledge on various functions defined in Python.

Also read:

Leave a Reply

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