Open In App

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
Practice Tags :

Similar Reads