Split a string and get the last element in Python

avatar

Borislav Hadzhiev

Last updated: Jun 25, 2022

banner

Photo from Unsplash

Split a string and get the last element in Python #

Use the str.rsplit() method with maxsplit set to 1 to split a string and get the last element. The rsplit() method splits from the right and will only perform a single split when maxsplit is set to 1.

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

We used the rsplit() method to split the string from the right.

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.

The last step is to access the last element in the list by accessing the list item at index -1.

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

You can also use the str.split() method in a similar way.

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

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

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

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

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

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

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.