Replace Multiple Words with K Python (original) (raw)

Last Updated : 4 Nov, 2025

The task is to replace all occurrences of specific words in a string with a single replacement word K. For example:

text = "apple orange banana"
words_to_replace = ["apple", "banana"]
**Output: "K orange K"

Let’s explore multiple methods to achieve this in Python.

Using List Comprehension

In this method, we split the string into words using split() method and check if each word matches any target word in the list. 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' li = ["best", "CS", "for"] k = "gfg" 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:

Using re.sub() with Regex

Here 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' li = ["best", "CS", "for"] k = "gfg"

res = re.sub("|".join(sorted(li, key=len, reverse=True)), k, s) print(res)

`

Output

Geeksgfggeeks is gfg gfg geeks and gfg

**Explanation: ``

Using for loop and replace()

This method iterates through each target word and replaces all its occurrences in the string using replace().

Python `

s = "Geeksforgeeks is best for geeks and CS" li = ["best", "CS", "for"] k = "gfg"

for word in li: s = s.replace(word, k) print(s)

`

Output

Geeksgfggeeks is gfg gfg geeks and gfg

**Explanation:

Using Lambda and reduce()

In this approach we use reduce() method from functools module and a lambda function, 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' li = ["best", 'CS', 'for'] k = 'gfg'

res = reduce(lambda s, w: s.replace(w, k), li, s) print(res)

`

Output

Geeksgfggeeks is gfg gfg geeks and gfg

**Explanation: