Open In App

Replace Multiple Words with K - Python

Last Updated : 04 Nov, 2025
Comments
Improve
Suggest changes
4 Likes
Like
Report

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:

  • s.split() splits the string into words.
  • [k if word in li else word for word in s.split()] checks each word; if it’s in li, it replaces it with k.
  • ' '.join(...) joins the modified words back into a single string.

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:

  • "|".join(...) creates a regex pattern matching any target word.
  • re.sub(pattern, k, s) replaces all occurrences of the pattern with k.
  • Sorting by length ensures longer words are replaced first to avoid partial matches.

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:

  • s.replace(word, k) replaces all occurrences of word with k.
  • The loop iterates over all target words in li.

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:

  • reduce(lambda s, w: s.replace(w, k), li, s) applies the lambda function for each word in li.
  • Lambda function: lambda s, w: s.replace(w, k) replaces w with k in the string s.

Explore