Python Split String at Last Occurrence

5/5 - (3 votes)

Summary:  Use given_string.rsplit('sep', 1) to split the string at the last occurrence. Another approach to solve the problem is to use given_string.rpartition('sep')

Minimal Example:

text = 'Fred fed Ted bread and Ted fed Fred bread'
# Method 1
print(text.rsplit('fed', 1))
# OUTPUT: ['Fred fed Ted bread and Ted ', ' Fred bread']

# Method 2
li = list(text.rpartition('fed'))
li.remove(li[1])
print(li)
# OUTPUT: ['Fred fed Ted bread and Ted ', ' Fred bread']

Problem Formulation

 📜Problem: Given a string. How will you split the string at the last occurrence?

Example

Consider that you are given a string with multiple occurrences of the word “scream”. You have to split the string at the last occurrence of the word “scream”.

# Input:
text = 'I scream, you scream, we all scream for ice cream'
# Expected Output:
['I scream, you scream, we all ', ' for ice cream']

Let’s dive into the different ways of solving the given problem.

Method 1: Using rsplit

Prerequisite: The rsplit() method splits a given string based on a given separator and stores the characters/substrings into a list. For example, finxterx123.rsplit('x') will return the list ['fin', 'ter', '123'] as an output.

  • rsplit can take two arguments:
    • sep – The separator string on which it is split.
    • maxsplit – The number of times the string is split.

🌎Read more here: Python String rsplit()

Approach: As we have to split the string only once at the last occurrence, we can use the maxsplit argument to solve the given problem by setting the maxsplit = 1. Therefore, the string will split along the specified separator only once from the right end. 

Code:

text = 'I scream, you scream, we all scream for ice cream'
print(text.rsplit('scream', 1))

# OUTPUT: ['I scream, you scream, we all ', ' for ice cream']

Method 2: Using rpartition

Prereqiuiste: The rpartition()  method searches for a separator substring and returns a tuple with three strings: (1) everything before the separator, (2) the separator itself, and (3) everything after it. For example: finxterx123'.rpartition('x') will return the following tuple: ('finxter', 'x', '123')

🌎Read more here: Python String rpartition()

Code:

text = 'I scream, you scream, we all scream for ice cream'
li = list(text.rpartition('scream'))
li.remove(li[1])
print(li)
# OUTPUT: ['I scream, you scream, we all ', ' for ice cream']

Explanation: Here, we have used the string “scream” as the separator. The rpartition() method splits the string when it finds the ‘scream’ separator. Now, a problem here is the word “scream” is also stored as an item within the list. This is all right if you want to keep the separator. However, in this case we do not need the separator. Hence, we use the remove() method to eliminate the second element (at index 1) where the separator is stored.

Bonus: rsplit() vs rpartition() 

  • If you are using the split() function, it will split the string at each occurrence of the given delimiter. It returns a list of the words in the string. Similarly we have a method known as rsplit(). It works the same as the split() function with the only difference being that the rsplit() function splits from the right end of the string.
  • Whereas, if you use the partition() function, it will split the string at the first occurrence of the separator. It returns a tuple containing 3 elements the part before the separator, the separator itself, and the part after the separator. Similarly we have a method known as rpartition(). It works the same as the partition() function with the only difference being that the rpartition() function splits the string at the last occurrence.

Example:

col = "black-red-pink-yellow"
print(col.split("-", 1))
print(col.rsplit("-", 1))

print(col.partition("-"))
print(col.rpartition("-"))

Output

['black', 'red-pink-yellow']
['black-red-pink', 'yellow']
('black', '-', 'red-pink-yellow')
('black-red-pink', '-', 'yellow')
  • When you are using the rsplit() function, and no separator or delimiter is mentioned, the function will split the string based on the occurrence of whitespaces. Whereas, if  a separator or delimiter isn’t mentioned while using the rpartition() function, it’ll raise a TypeError.
col = "black-red pink-yellow blue"
print(col.rsplit())

try:
    print(col.rpartition())
except Exception as e:
    print(e)

Output

['black-red', 'pink-yellow', 'blue']

str.rpartition() takes exactly one argument (0 given)

Basically, the main difference between the two functions is that the rsplit() method will split the string at any occurrence of the given argument unless a maxsplit argument is specified, while the rpartition() will only split the string at the last occurrence.

Conclusion

I hope the methods to solve the problem used in this tutorial helped you to learn how to split a string at the last occurrence of a specified delimiter. Please subscribe and stay tuned for more interesting tutorials and solutions.

🌎Recommended Read: Python | Split String and Get Last Element


But before we move on, I’m excited to present you my new Python book Python One-Liners (Amazon Link).

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

Link: https://nostarch.com/pythononeliners