w3resource

Python: Split a string on the last occurrence of the delimiter


Split string on last delimiter occurrence.

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

Python String Exercises: Split a string on the last occurrence of the delimiter

Sample Solution:

Python Code:

# Define a string 'str1' containing a comma-separated list of characters.
str1 = "w,3,r,e,s,o,u,r,c,e"

# Split the string 'str1' into a list of substrings using the ',' separator, starting from the right.
# Split at most 1 time and print the result.
print(str1.rsplit(',', 1))

# Split the string 'str1' into a list of substrings using the ',' separator, starting from the right.
# Split at most 2 times and print the result.
print(str1.rsplit(',', 2))

# Split the string 'str1' into a list of substrings using the ',' separator, starting from the right.
# Split at most 5 times and print the result.
print(str1.rsplit(',', 5)) 

Sample Output:

['w,3,r,e,s,o,u,r,c', 'e']                                                                                    
['w,3,r,e,s,o,u,r', 'c', 'e']                                                                                 
['w,3,r,e,s', 'o', 'u', 'r', 'c', 'e']               

Flowchart:

Flowchart: Split a string on the last occurrence of the delimiter

For more Practice: Solve these Related Problems:

  • Write a Python program to split a string into two parts based on the last occurrence of a specified delimiter using rpartition().
  • Write a Python program to implement a function that returns the substring before the last occurrence of a delimiter.
  • Write a Python program to locate the last delimiter in a string using rfind() and split the string accordingly.
  • Write a Python program to use slicing to separate a string into two segments at the final delimiter occurrence.

Go to:


Previous: Write a Python program to count and display the vowels of a given text.
Next: Write a Python program to find the first non-repeating character in given string

Python Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.