Remove Last Word From String in Python

In this tutorial, we will discuss how to remove the last word in a block of Python string, as shown in the example image below.

Remove the last word in a string (Source: Author)

There are several ways to do this, but the critical point is that any method will depend on finding the last whitespace in the string, which is the words delimiter in most cases. Slicing the string at that point will separate the last word from the rest of the block text.

Note: In some cases, there’s a white space at the end of the string – in most cases, we will remove that first using str.rstrip() and then continue to remove the last word. Let’s now discuss some methods to remove the last word from the string.

Method 1: Using str.rfind() function

The str.rfind() functions find the highest index where the substring is found in the string – that is the last appearance of the substring we are looking for. Here is an example,

string1 = "I am coming home "
string_removed = string1[:string1.rstrip().rfind(" ")]
print(string_removed)

Output:

I am coming

The function rfind(” “) returns the index for the last white space then we slice string1 from the start to where the last white space is found.

Method2: Using str.rsplit() function

The function string1.rsplit(sub, n) function returns a list of strings after making n splits in string1 starting from the right.

string2 = "Python is powerful languange"
string2_removed = string2.rsplit(" ", 1)[0]
print(string2_removed)

Output:

Python is powerful

In this snippet, we use rsplit(” “, 1) to look for the first occurrence of whitespace (” “) from the right. That returns a list. To finish the process, we extract the required string at index 0.

Method 3: Split() and join()

Python’s inbuilt str module also allows us to split and join strings. The str1.split(sep,n) returns a list of strings after splitting str1 at most n splits. On the other hand, str.join(iterable) joins an iterable, like list, through concatenation.

Example:

str1 = "The coding game"
list_words = str1.split()[:-1]
join_words = " ".join(list_words)
print(join_words)

Output:

The coding

The split() function splits str1 into a list of strings (splits using whitespace by default) [“The”, “coding”, “game”] then we slice using [:-1] to exclude the last word on the list. Lastly, we joined the words on the resulting list with whitespace.

Method 4: Using regular expressions (using re package in Python)

The re package can be used to find patterns. In our case, we will look for whitespaces (“\s“) or non-whitespaces (“\S“).

import re
str_re = " Thank you for the good.work"
list_words = re.findall(r'\S+', str_re)[:-1]
join_re = " ".join(list_words)
print(join_re)

Output:

Thank you for the

In this case, we use re to find all non-whitespace (“\S”) of at least one character (“+”). The result is a list of words we can slice and join as we did in Method 3.

Practical example

Suppose we have a text file named last_word2.txt  which contains a random string at the end of every line, as shown below. The objective is to remove the random string from the line and save a clean text file as clean.txt.

The code:

#open clean.txt file as write mode (w)
#if the file does not exist, it is created otherwise replaced
f = open("clean.txt", "w")
#Open last_word2.txt as read only (r)
with open("last_word2.txt", "r") as fp:
    # Read line by line in a for-loop
    for line in fp:
   	 # remove whitespace at the end and beginning of line
   	 line = line.strip()
   	 # remove the last word by finding first space from right
   	 clean_line = line[:line.rfind(" ")]
   	 # Write a clean line to clean.txt
   	 f.write(clean_line+"\n")
# clean.txt
f.close()

Output (clean.txt):

And the lines are free of the random text we had before now. This is just a simple application of the concepts we learned in this article. As you continue to work on problems and projects, you will find the ideas discussed becoming important.