Remove the last word from a String in Python

avatar

Borislav Hadzhiev

Last updated: Aug 19, 2022

banner

Photo from Unsplash

Remove the last word from a String in Python #

To remove the last word from a string:

  1. Use the str.rsplit() method to split the string on a space, once, from the right.
  2. Access the first list item.
  3. The first list item stores the part of the string before the last word.
main.py
my_str = 'one two three four five' # ✅ Remove last word from string (using str.rsplit()) new_str = my_str.rsplit(' ', 1)[0] print(new_str) # 👉️ 'one two three four' # -------------------------------- # ✅ Remove last word from string (using str.rindex()) new_str = my_str[:my_str.rindex(' ')] print(new_str) # 👉️ 'one two three four'

The first example uses the str.rsplit() method to remove the last word from a string.

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 four five' # 👇️ ['one two three four', 'five'] print(my_str.rsplit(' ', 1))

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().

In its entirety, the example splits the string on a space, once, from the right and returns the first list item.

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

This approach also works if the string contains a single word or is empty.

main.py
my_str = 'one' # 👇️ ['one'] print(my_str.rsplit(' ', 1)) new_str = my_str.rsplit(' ', 1)[0] print(new_str) # 👉️ 'one'
If the provided separator is not found in the string, the str.rsplit() method returns a list containing a single string.

In this case, we access the list at index 0 and return the entire string.

Alternatively, you can use string slicing.

Remove the last word from a String using sting slicing #

To remove the last word from a string:

  1. Use the str.rindex() method to get the index of the last space in the string.
  2. Use string slicing to get a slice of the string up to the index of the last space.
  3. The new string won't contain the last word of the original string.
main.py
my_str = 'one two three four five' new_str = my_str[:my_str.rindex(' ')] print(new_str) # 👉️ 'one two three four'

We used the str.rindex() method to get the index of the last word in the string.

The str.rindex method returns the highest index in the string where the provided substring is found.

main.py
my_str = 'one two three four five' print(my_str.rindex(' ')) # 👉️ 18

The method raises ValueError when the provided substring is not found in the string.

main.py
my_str = 'one' # ⛔️ ValueError: substring not found print(my_str.rindex(' '))
The str.rindex() method is very similar to str.rfind() but it raises ValueError, instead of returning -1 if the substring is not present in the string.

You can use a try/except statement if you need to handle the error in any way.

main.py
my_str = 'one' try: new_str = my_str[:my_str.rindex(' ')] print(new_str) except ValueError: # 👇️ this runs pass
The string in the example doesn't contain any spaces, so a ValueError is raised and is then handled by the except block.

The string slice my_str[:my_str.rindex(' ')] selects the part of the string up to the last word.

The syntax for string slicing is my_str[start:stop:step].

The start index is inclusive, whereas the stop index is exclusive (up to, but not including).

If a value for the start index is not specified, we start at the beginning of the string.

Python indexes are zero-based, so the first character in a string has an index of 0, and the last character has an index of -1 or len(my_str) - 1.

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.