Python | Replace rear word in String

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output :



The original string is : GFG is good
The String after performing replace : GFG is best

 

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 string using rfind() and join() is used to perform replace.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output :

The original string is : GFG is good
The String after performing replace : GFG is best


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.