Python - Replace rear word in String


In this article we will learn how we can replace rear (word at the end of the string) word with any other given word. You may have seen this problem while doing manipulation of string. Here we will see various methods for replacing the rear word in string with given word.

Let’s get to know this using below example −

string_txt = "This cat is running very Fast"

Here we have a string string_txt which contains sentences and we want to replace the last word which is "Fast" into "Slow" so that the resulting string will be like.

string_txt = "This cat is running very Slow"

Methods to perform this operation.

Method 1. Using Split() and Join() Functions.

Example

def replace_rear(string_txt, new_str):
   words = string_txt.split()
   words[-1] = new_str
   return ' '.join(words)
   
string_txt = "This cat is running very Fast"
print("String before replace: ", string_txt)
new_string = replace_rear(string_txt, "Slow")
print("String after replacing rear: ", new_string)

Output

String before replace: This cat is running very Fast 
String after replacing rear: This cat is running very Slow

Explanation

Here in the above example we used split() method to separate the string into list of words. We access the last word using words[-1] and replace this word using new_str which is new word which we want to replace with the last word. Then we used join() method to combine back the list words into string.

Method 2. Using Regular Expressions.

Example

import re

def replace_rear(string_txt, new_str):
   return re.sub(r'\b\w+\b$', new_str, string_txt)
   
string_txt = "This cat is running very Fast"
print("String before replace: ", string_txt)
new_string = replace_rear(string_txt, "Slow")
print("String after replacing rear: ", new_string)

Output

String before replace: This cat is running very Fast 
String after replacing rear: This cat is running very Slow

Explanation

Here in the above example we used the re.sub() method from regular expressions to perform the regular expression substitution. We defined a pattern r'\b\w+\b$' which matches the last word of the string and replaced it with the new_str.

Method 3. Using Rsplit() Function.

Example

import re

def replace_rear(string_txt, new_str):
   words = string_txt.rsplit(None, 1)
   return words[0] + ' ' + new_str
   
string_txt = "This cat is running very Fast"
print("String before replace: ", string_txt)
new_string = replace_rear(string_txt, "Slow")
print("String after replacing rear: ", new_string)

Output

String before replace: This cat is running very Fast 
String after replacing rear: This cat is running very Slow

Explanation

Here in the above example we used rsplit() method which allows us to split a string from the right most side. So, we used this method to split the string into words starting from the right side. We define the separator as None and number of split as 1, because we want only the last one word to be replaced. Then we combine the split string with new_str. So, it will eventually replace the word with the given new word.

Method 4. Using List Comprehension.

Example

import re

def replace_rear(string_txt, new_str):
   words = string_txt.split()
   words = [new_str if i == len(words) - 1 else word for i, word in enumerate(words)]
   return ' '.join(words)
   
string_txt = "This cat is running very Fast"
print("String before replace: ", string_txt)
new_string = replace_rear(string_txt, "Slow")
print("String after replacing rear: ", new_string)

Output

String before replace: This cat is running very Fast 
String after replacing rear: This cat is running very Slow

Explanation

Here in the above example we used list comprehension to traverse on the words and replaced the last word when we reached at the last index len(words)-1. Then we use the join() function to combine the splitted string back. So, our new string contains the replaced word at the end.

Method 5. Using String Slicing Technique.

Example

import re

def replace_rear(string_txt, new_str):
   last_space_index = string_txt.rindex(' ')
   return string_txt[:last_space_index+1] + new_str
   
string_txt = "This cat is running very Fast"
print("String before replace: ", string_txt)
new_string = replace_rear(string_txt, "Slow")
print("String after replacing rear: ", new_string)

Output

String before replace: This cat is running very Fast 
String after replacing rear: This cat is running very Slow

Explanation

Here in the above example we used string slicing technique to replace the string last word with the new word. We first find the last space of the string using rindex() then using slicing we split the string up to the last index and then we combine it with the space and append the new word which we want to replace.

Method 6. Using Split(), Maxsplit and Join() Methods.

Example

import re

def replace_rear(string_txt, new_str):
   words = string_txt.split(maxsplit=string_txt.count(' ') or None)
   words[-1] = new_str
   return ' '.join(words)
   
string_txt = "This cat is running very Fast"
print("String before replace: ", string_txt)
new_string = replace_rear(string_txt, "Slow")
print("String after replacing rear: ", new_string)

Output

String before replace: This cat is running very Fast 
String after replacing rear: This cat is running very Slow

Explanation

Here in the above example we used maxsplit=string_txt.count('') or None to specify that the string split will occur at the last space. Then after slitting the last word we replaced the last word with the new_str and using the join() function we combined the splitted string back

So, we get to know about methods to replace the last word of string with new word. We saw various approach to solve the problem which include regular expressions, list comprehension, split() and rsplit() functions. Each method has its unique approach to solve the problem, you can choose any method which is suitable and easy according to your need.

Updated on: 03-Oct-2023

55 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements