Split string on last occurrence of delimiter in Python

avatar

Borislav Hadzhiev

Last updated: Jun 25, 2022

banner

Photo from Unsplash

Split string on last occurrence of delimiter in Python #

Use the str.rsplit() method with maxsplit set to 1 to split a string on the last occurrence of a delimiter, e.g. my_str.rsplit(',', 1). The rsplit() method splits from the right, and only performs a single split when maxsplit is set to 1.

main.py
my_str = 'one,two,three,four' my_list = my_str.rsplit(',', 1) print(my_list) # 👉️ ['one,two,three', 'four'] print(my_list[0]) # 👉️ one,two,three print(my_list[1]) # 👉️ four first, second = my_list print(first) # 👉️ 'one,two,three' print(second) # 👉️ 'four'

We used the str.rsplit() method to split a string on the last occurrence of the provided delimiter.

The str.rsplit method returns a list of the words in the string using the provided separator as the delimiter string.

main.py
my_str = 'one two three' print(my_str.rsplit(' ')) # 👉️ ['one', 'two', 'three'] print(my_str.rsplit(' ', 1)) # 👉️ ['one two', 'three']

The method takes the following 2 arguments:

NameDescription
separatorSplit the string into substrings on each occurrence of the separator
maxsplitAt most maxsplit splits are done, the rightmost ones (optional)

Except for splitting from the right, rsplit() behaves like split().

When the maxsplit argument is set to 1, at most 1 split is done.

If the separator is not found in the string, a list containing only 1 element is returned.

main.py
my_str = 'one two three four' my_list = my_str.rsplit('-', 1) print(my_list) # 👉️ ['one two three four']

If your string ends with the specific separator, you might get a confusing result.

main.py
my_str = 'one-two-three-four-' my_list = my_str.rsplit('-', 1) print(my_list) # 👉️ ['one-two-three-four', '']

You can use the str.strip() method to remove the leading or trailing separator.

main.py
my_str = '-one-two-three-four-' my_list = my_str.strip('-').rsplit('-', 1) print(my_list) # 👉️ ['one-two-three', 'four']

We used the str.strip() method to remove any leading or trailing hyphens from the string before calling the rsplit() method.

If you need to assign the results from the list to variables, unpack the values from the list.

main.py
my_str = 'one-two-three-four' my_list = my_str.rsplit('-', 1) print(my_list) # 👉️ ['one-two-three', 'four'] first, second = my_list print(first) # 👉️ one-two-three print(second) # 👉️ four

The first and second variables store the first and second items from the list.

When using this approach, we have to be sure to declare exactly as many variables as there are items in the iterable.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.