Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Random Replacement of Word in String
Next article icon

Python | Replace rear word in String

Last Updated : 23 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, while working with String list, we can have a problem in which we need to replace the most rear i.e last word of string. This problem has many application in web development domain. Let’s discuss different ways in which this problem can be solved. 

Method #1 : Using split() + join() This is one way in which we can perform this task. In this, we break elements into parts and then return the last value and perform the addition of new element using join(). 

Python3




# Python3 code to demonstrate working of
# Rear word replace in String
# using split() + join()
 
# initializing string
test_str = "GFG is good"
 
# printing original string
print("The original string is : " + test_str)
 
# initializing replace string
rep_str = "best"
 
# Rear word replace in String
# using split() + join()
res = " ".join(test_str.split(' ')[:-1] + [rep_str])
 
# printing result
print("The String after performing replace : " + res)
 
 
Output
The original string is : GFG is good The String after performing replace : GFG is best

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #2 : Using rfind() + join() The combination of these functions can also be used to perform this task. In this, we perform the task of extracting the last word of the string using rfind() and join() is used to perform replace. 

Python3




# Python3 code to demonstrate working of
# Rear word replace in String
# using rfind() + join()
 
# initializing string
test_str = "GFG is good"
 
# printing original string
print("The original string is : " + test_str)
 
# initializing replace string
rep_str = "best"
 
# Rear word replace in String
# using rfind() + join()
res = test_str[: test_str.rfind(' ')] + ' ' + rep_str
 
# printing result
print("The String after performing replace : " + res)
 
 
Output
The original string is : GFG is good The String after performing replace : GFG is best

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #3 : Using split(),pop(),append() and join() methods

Python3




# Python3 code to demonstrate working of
# Rear word replace in String
 
# initializing string
test_str = "GFG is good"
 
# printing original string
print("The original string is : " + test_str)
 
# initializing replace string
rep_str = "best"
 
# Rear word replace in String
x = test_str.split()
x.pop()
x.append(rep_str)
res = " ".join(x)
# printing result
print("The String after performing replace : " + res)
 
 
Output
The original string is : GFG is good The String after performing replace : GFG is best

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #4:Using split(),indexing, list(),join() functions

Python3




# Python3 code to demonstrate working of
# Rear word replace in String
 
# initializing string
test_str = "GFG is good"
 
# printing original string
print("The original string is : " + test_str)
 
# initializing replace string
rep_str = "best"
 
list_words = list(test_str.split())
list_words[-1] = rep_str
res = " ".join(list_words)
 
# printing result
print("The String after performing replace : " + res)
 
 
Output
The original string is : GFG is good The String after performing replace : GFG is best

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #5 : Using regex

Python3




import re
 
#initializing string
test_str = "GFG is good"
 
#printing original string
print("The original string is : " + test_str)
 
#initializing replace string
rep_str = "best"
 
#Rear word replace in String
res = re.sub(r'\b[\w-]+\b(?=\s*$)', rep_str, test_str)
 
#printing result
print("The String after performing replace : " + res)
 
 
Output
The original string is : GFG is good The String after performing replace : GFG is best

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #6: Using  str.rsplit()

Python3




test_str = "GFG is good"
rep_str = "best"
#printing original string
print("The original string is : " + test_str)
words = test_str.rsplit(maxsplit=1)
words[-1] = rep_str
res = " ".join(words)
print("The String after performing replace : " + res)
#This code is contributed by Jyothi pinjala
 
 
Output
The original string is : GFG is good The String after performing replace : GFG is best

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 7: Using rpartition() function

Step-by-step approach:

  • Initialize the original string and print it.
  • Initialize the replace string.
  • Use rpartition() function to split the string into three parts: string before the last occurrence of space,space, and the last word.
  • Concatenate the first two parts with the replace string and space separator.
  • Store the result in a variable.
  • Print the result.

Python3




# initializing string
test_str = "GFG is good"
 
# printing original string
print("The original string is : " + test_str)
 
# initializing replace string
rep_str = "best"
 
# using rpartition() function to split the string
first, sep, last = test_str.rpartition(' ')
 
# replacing the last word with replace string
last = rep_str
 
# concatenate the first two parts and the replace string with space separator
res = first + sep + last
 
# printing result
print("The String after performing replace : " + res)
 
 
Output
The original string is : GFG is good The String after performing replace : GFG is best 

Time complexity: O(n), where n is the length of the string.
Auxiliary space: O(n), for storing the result in a variable.



Next Article
Python - Random Replacement of Word in String
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Python - Random Replacement of Word in String
    Given a string and List, replace each occurrence of K word in string with random element from list. Input : test_str = "Gfg is x. Its also x for geeks", repl_list = ["Good", "Better", "Best"], repl_word = "x" Output : Gfg is Best. Its also Better for geeks Explanation : x is replaced by random repla
    3 min read
  • Remove spaces from a string in Python
    Removing spaces from a string is a common task in Python that can be solved in multiple ways. For example, if we have a string like " g f g ", we might want the output to be "gfg" by removing all the spaces. Let's look at different methods to do so: Using replace() methodTo remove all spaces from a
    2 min read
  • Replace substring in list of strings - Python
    We are given a list of strings, and our task is to replace a specific substring within each string with a new substring. This is useful when modifying text data in bulk. For example, given a = ["hello world", "world of code", "worldwide"], replacing "world" with "universe" should result in ["hello u
    3 min read
  • Python | Remove unwanted spaces from string
    Sometimes, while working with strings, we may have situations in which we might have more than 1 spaces between intermediate words in strings that are mostly unwanted. This type of situation can occur in web development and often needs rectification. Let's discuss certain ways in which this task can
    4 min read
  • Python - Wildcard Substring search
    Sometimes, while working with Python Strings, we have problem in which, we need to search for substring, but have some of characters missing and we need to find the match. This can have application in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using re.s
    6 min read
  • Python - Word starting at Index
    Sometimes, while working with Python, we can have a problem in which we need to extract the word which is starting from a particular index. This can have a lot of applications in school programming. Let's discuss certain ways in which this task can be performed. Method #1: Using a loop This is a bru
    2 min read
  • Python - Reverse Range in String List
    Given a string list, reverse each element of string list from ith to jth index. Input : test_list = ["Geeksforgeeks", "Best", "Geeks"], i, j = 1, 2 Output : ['ee', 'es', 'ee'] Explanation : Range of strings are extracted. Input : test_list = ["Geeksforgeeks"], i, j = 1, 7 Output : ['eeksfor'] Explan
    3 min read
  • Replace Substrings from String List - Python
    The task of replacing substrings in a list of strings involves iterating through each string and substituting specific words with their corresponding replacements. For example, given a list a = ['GeeksforGeeks', 'And', 'Computer Science'] and replacements b = [['Geeks', 'Gks'], ['And', '&'], ['C
    3 min read
  • Replace multiple words with K - Python
    We are given a string s and the task is to replace all occurrences of specified target words with a single replacement word K.For example, given text = "apple orange banana" and words_to_replace = ["apple", "banana"], the output will be "K orange K". Using List ComprehensionThis is the most efficien
    4 min read
  • Word location in String - Python
    Word location in String problem in Python involves finding the position of a specific word or substring within a given string. This problem can be approached using various methods in Python, such as using the find(), index() methods or by regular expressions with the re module. Using str.find()str.f
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences