w3resource

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

Python String: Exercise-50 with Solution

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

Python Code Editor:

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

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.