Replace multiple words with K - Python
Last Updated : 18 Jan, 2025
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)
OutputGeeksforgeeks 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)
OutputGeeksgfggeeks 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)
OutputGeeksgfggeeks 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)
OutputGeeksgfggeeks 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))
OutputGeeksgfggeeks is gfg gfg geeks and gfg
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 l
3 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 - 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