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 - Replace all words except the given word
Next article icon

Replace multiple words with K – Python

Last Updated : 18 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 Comprehension

This is the most efficient approach in which we split the string s into words using the split() method and check if each word matches any target word in the list li. If it does then we replace it with the replacement word K, then join the modified list back into a single string using join() method.

Python
s = 'Geeksforgeeks is best for geeks and CS'  # List of words to replace li = ["best", "CS", "for"]  # Replacement word k = "gfg"  # Replace words in the list with the replacement word res = ' '.join([k if word in li else word for word in s.split()])  print(res) 

Output
Geeksforgeeks is gfg gfg geeks and gfg 

Explanation:

  • Here using list comprehension we iterate over each word in the string s (split into a list of words) and if a word is in the target word list li then it is replaced with the replacement word K otherwise it remains unchanged.

Using regex

In this method we use regular expressions (regex) to match any word from the target list and replace them with the replacement word K.

Python
import re  s = 'Geeksforgeeks is best for geeks and CS'  # List of words to replace li = ["best", "CS", "for"]  # Replacement word k = "gfg"  # Replace words using regex res = re.sub("|".join(sorted(li, key=len, reverse=True)), k, s)  print(res) 

Output
Geeksgfggeeks is gfg gfg geeks and gfg 

Explanation: re.sub(pattern, replacement, input_string) searches for the pattern in the input string and replaces it with the replacement word.

Using for loop and replace()

In this method we use for loop to iterate through each word in the list li and then use the replace() method to replace all occurrences of that word in the string s with the replacement word K.

Python
s = "Geeksforgeeks is best for geeks and CS"  # Input string li = ["best", "CS", "for"]  # Words to replace k = "gfg"  # Replacement word  # Replace each word in l with r for word in li:     s = s.replace(word, k)  print(s) 

Output
Geeksgfggeeks is gfg gfg geeks and gfg 

Using Lambda and reduce()

In this approach we use the reduce() method from the functools module and a lambda function, the reduce() method applies the lambda function to each element in the list cumulatively, replacing the words with the specified replacement word K.

Python
from functools import reduce  s = 'Geeksforgeeks is best for geeks and CS'  # Input string li = ["best", 'CS', 'for']  # List of words to replace k = 'gfg'  # Replacement word  # Replace words in the list with the replacement word res = reduce(lambda s, w: s.replace(w, k), li, s)  print(res) 

Output
Geeksgfggeeks is gfg gfg geeks and gfg 

Explanation:

  • reduce() function applies the lambda function cumulatively to the elements of the list li (which contains words to replace) and modifies the string s by replacing each word with the replacement word k.
  • lambda function ( lambda s, w: s.replace(w, r) defines an anonymous function that takes two arguments: the current string s and the word w to replace, it uses s.replace(w, r) to replace each occurrence of w in s with the word k.

Using Heapq

We use the heapq module to replace multiple words in a string, The words are converted into tuples with the negative length (for max-heap behavior in python), followed by the word and the replacement word K. Once we build the heap with heapq.heapify(), we pop elements and replace occurrences of the popped word in the string with K.

Python
import heapq  # initialize the input string and list of words to replace s = 'Geeksforgeeks is best for geeks and CS' li = ["best", 'CS', 'for'] k = 'gfg'  # create a heap from the word_list heap = [(-len(word), word, k) for word in li] heapq.heapify(heap)  # replace the words in the text using heapq while heap:     _, word, repl = heapq.heappop(heap)     s = s.replace(word, repl)  print(str(s)) 

Output
Geeksgfggeeks is gfg gfg geeks and gfg 


Next Article
Python - Replace all words except the given word
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Python - Replace K with Multiple values
    Sometimes, while working with Python Strings, we can have a problem in which we need to perform replace of single character/work with particular list of values, based on occurrence. This kind of problem can have application in school and day-day programming. Let's discuss certain ways in which this
    5 min read
  • Python | Replace punctuations with K
    Sometimes, while working with Python Strings, we have a problem in which we need to perform the replacement of punctuations in String with specific characters. This can have applications in many domains such as day-day programming. Let's discuss certain ways in which this task can be performed. Meth
    7 min read
  • Multiple Indices Replace in String - Python
    In this problem, we have to replace the characters in a string at multiple specified indices and the following methods demonstrate how to perform this operation efficiently: Using loop and join()join() is a brute force method where we first convert the string into a list then we iterate through the
    3 min read
  • Python - Replace Non-None with K
    Sometimes, while working with Python lists we can have a problem in which we need to perform the replacement of all the elements that are non-None. This kind of problem can have applications in many domains such as web development and day-day programming. Let's discuss certain ways in which this tas
    6 min read
  • Python - Replace all words except the given word
    Given a string. The task is to replace all the words with '?' except the given word K. Examples: Input : test_str = 'gfg is best for geeks', K = "gfg", repl_char = "?" Output : gfg ? ? ? ? Explanation : All words except gfg is replaced by ?. Input : test_str = 'gfg is best for gfg', K = "gfg", repl_
    6 min read
  • Python - Words with Particular Rear letter
    Sometimes, we require to get the words that end with the specific letter. This kind of use case is quiet common in the places of common programming projects or competitive programming. Let’s discuss certain shorthands to deal with this problem in Python. Method #1: Using list comprehension + lower()
    6 min read
  • Python - Move Word to Rear end
    Sometimes, while working with Python strings, we can have a problem in which we need to find a word and move it to the end of the string. This can have application in many domains, including day-day programming and school programming. Let's discuss certain ways in which this task can be performed. M
    6 min read
  • 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 i
    5 min read
  • Python - Replace words from Dictionary
    Replacing words in a string using a dictionary allows us to efficiently map specific words to new values. Using str.replace() in a LoopUsing str.replace() in a loop, you can systematically replace specific substrings within a string with new values. This approach is useful for repetitive replacement
    3 min read
  • Python - Count of Words with specific letter
    Given a string of words, extract the count of words with a specific letters. Input : test_str = 'geeksforgeeks is best for geeks', letter = "g" Output : 2 Explanation : "g" occurs in 2 words. Input : test_str = 'geeksforgeeks is best for geeks', letter = "s" Output : 4Explanation : "s" occurs in 4 w
    8 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