Open In App

Python – Replace multiple words with K

Last Updated : 12 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python strings, we can have a problem in which we need to perform a replace of multiple words with a single word. This can have application in many domains including day-day programming and school programming. Lets discuss certain ways in which this task can be performed. 

Method #1 : Using join() + split() + list comprehension The combination of above functions can be used to perform this task. In this, we split the string into words, check and replace the list words using join and list comprehension. 

Python3




# Python3 code to demonstrate working of
# Replace multiple words with K
# Using join() + split() + list comprehension
 
# initializing string
test_str = 'Geeksforgeeks is best for geeks and CS'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing word list
word_list = ["best", 'CS', 'for']
 
# initializing replace word
repl_wrd = 'gfg'
 
# Replace multiple words with K
# Using join() + split() + list comprehension
res = ' '.join([repl_wrd if idx in word_list else idx for idx in test_str.split()])
 
# printing result
print("String after multiple replace : " + str(res))


Output : 

The original string is : Geeksforgeeks is best for geeks and CS
String after multiple replace : Geeksforgeeks is gfg gfg geeks and gfg

Time complexity: O(n), where n is the number of words in the string “test_str”.
Auxiliary space: O(m), where m is the number of characters in the output string “res”. This is because the output string requires memory proportional to its length to store its characters.

Method #2: Using regex + join() The combination of above functions can be used to perform this task. In this, we find the words using regex and perform the replace using join() and list comprehension. 

Python3




# Python3 code to demonstrate working of
# Replace multiple words with K
# Using regex + join()
import re
 
# initializing string
test_str = 'Geeksforgeeks is best for geeks and CS'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing word list
word_list = ["best", 'CS', 'for']
 
# initializing replace word
repl_wrd = 'gfg'
 
# Replace multiple words with K
# Using regex + join()
res = re.sub("|".join(sorted(word_list, key = len, reverse = True)), repl_wrd, test_str)
 
# printing result
print("String after multiple replace : " + str(res))


Output : 

The original string is : Geeksforgeeks is best for geeks and CS
String after multiple replace : Geeksforgeeks is gfg gfg geeks and gfg

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #3 : Using for loop+replace() methods

Python3




# Python3 code to demonstrate working of
# Replace multiple words with K
 
 
# initializing string
test_str = 'Geeksforgeeks is best for geeks and CS'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing word list
word_list = ["best", 'CS', 'for']
 
# initializing replace word
repl_wrd = 'gfg'
 
# Replace multiple words with K
for i in word_list:
    test_str=test_str.replace(i,repl_wrd)
# printing result
print("String after multiple replace : " + str(test_str))


Output

The original string is : Geeksforgeeks is best for geeks and CS
String after multiple replace : Geeksgfggeeks is gfg gfg geeks and gfg

Time Complexity: O(n*m) where n is the length of the input string and m is the number of words in the word_list.
Auxiliary Space: O(n) as it only uses memory for storing the input string and the list of words.

Approach 4: Using dictionary and re.sub()
 

Python3




import re
 
def multiple_replace(text, word_dict):
# create a regular expression pattern from the dictionary keys
  pattern = re.compile("|".join(map(re.escape, word_dict.keys())))
  # use re.sub to replace the keys with values in the text
  return pattern.sub(lambda x: word_dict[x.group(0)], text)
 
#initialize the input string and dictionary of words to replace
text = 'Geeksforgeeks is best for geeks and CS'
word_dict = {"best": "gfg", "CS": "gfg", "for": "gfg"}
 
#replace the words in the text using the dictionary
result = multiple_replace(text, word_dict)
 
print("String after multiple replace : " + str(result))


Output

String after multiple replace : Geeksgfggeeks is gfg gfg geeks and gfg

Time Complexity: O(n), where n is the number of characters in the input string.
Auxiliary Space: O(n), as the pattern and result strings will require memory proportional to their length.

Approach #5: Using a lambda function with reduce() method.

We can use a lambda function with the reduce() method to replace multiple words in the given string with the specified word. The reduce() method takes a function and a sequence as input and applies the function cumulatively to the sequence elements from left to right, so that it reduces the sequence to a single value.

Step-by-step approach:

  1. Import the reduce() method from functools module.
  2. Define a lambda function that takes two parameters: a string and a word from the word_list, and replaces the word with the specified replacement word.
  3. Pass this lambda function and the word_list as input to the reduce() method, and apply it cumulatively to the given string from left to right.
  4. The final value of the string after multiple replacements is returned as output.

Python3




from functools import reduce
 
# initializing string
test_str = 'Geeksforgeeks is best for geeks and CS'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing word list
word_list = ["best", 'CS', 'for']
 
# initializing replace word
repl_wrd = 'gfg'
 
# Replace multiple words with K
replace_func = lambda s, w: s.replace(w, repl_wrd)
test_str = reduce(replace_func, word_list, test_str)
 
# printing result
print("String after multiple replace : " + str(test_str))


Output

The original string is : Geeksforgeeks is best for geeks and CS
String after multiple replace : Geeksgfggeeks is gfg gfg geeks and gfg

Time complexity: O(nk), where n is the length of the given string and k is the length of the word list.
Auxiliary space: O(n), where n is the length of the given string.

Approach 6: Using heapq:

Algorithm:

  1. Initialize the input string and list of words to replace.
  2. Create a heap from the word_list by converting each word into a tuple of the form (-len(word), word, repl_wrd), where -len(word) is the length of the word multiplied by -1 to make the heap behave like a max heap.
  3. Heapify the heap using the heapq.heapify() method.
  4. While the heap is not empty, pop the word with the largest length from the heap using heapq.heappop().
  5. Replace all occurrences of the popped word in the input string with the replacement word.
  6. Repeat steps 4 and 5 until the heap is empty.
  7. Return the modified input string.

Python3




import heapq
 
# initialize the input string and list of words to replace
text = 'Geeksforgeeks is best for geeks and CS'
word_list = ["best", 'CS', 'for']
repl_wrd = 'gfg'
# printing original string
print("The original string is : " + str(text))
# create a heap from the word_list
heap = [(-len(word), word, repl_wrd) for word in word_list]
heapq.heapify(heap)
 
# replace the words in the text using heapq
while heap:
    _, word, repl = heapq.heappop(heap)
    text = text.replace(word, repl)
 
print("String after multiple replace : " + str(text))
#This code is contributed by Pushpa.
 
#This code is contributed by Pushpa.


Output

The original string is : Geeksforgeeks is best for geeks and CS
String after multiple replace : Geeksgfggeeks is gfg gfg geeks and gfg

Time complexity: O(n log n) because it uses the heapq.heapify() method to create a heap with n elements, and then it pops elements from the heap n times, each time taking O(log n) time.

Auxiliary Space: O(n) because it creates a heap with n elements.



Similar Reads

replace() in Python to replace a substring
Given a string str that may contain one more occurrences of “AB”. Replace all occurrences of “AB” with “C” in str. Examples: Input : str = "helloABworld" Output : str = "helloCworld" Input : str = "fghABsdfABysu" Output : str = "fghCsdfCysu" This problem has existing solution please refer Replace all occurrences of string AB with C without using ex
1 min read
Python | Pandas Series.str.replace() to replace text in a series
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages that makes importing and analyzing data much easier. Pandas Series.str.replace() method works like Python .replace() method only, but it works on Series too. Before calling .replace() on a Panda
5 min read
Python - Replace words from Dictionary
Given String, replace it's words from lookup dictionary. Input : test_str = 'geekforgeeks best for geeks', repl_dict = {"geeks" : "all CS aspirants"} Output : geekforgeeks best for all CS aspirants Explanation : "geeks" word is replaced by lookup value. Input : test_str = 'geekforgeeks best for geeks', repl_dict = {"good" : "all CS aspirants"} Outp
4 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_char = "?" Output : gfg ? ? ? gfg Explanation : Al
6 min read
Python - Compute the frequency of words after removing stop words and stemming
In this article we are going to tokenize sentence, paragraph, and webpage contents using the NLTK toolkit in the python environment then we will remove stop words and apply stemming on the contents of sentences, paragraphs, and webpage. Finally, we will Compute the frequency of words after removing stop words and stemming. Modules Needed bs4: Beaut
8 min read
Python | Replace multiple occurrence of character by single
Given a string and a character, write a Python program to replace multiple occurrences of the given character by a single character. Examples: Input : Geeksforgeeks, ch = 'e' Output : Geksforgeks Input : Wiiiin, ch = 'i' Output : WinReplace multiple occurrence of character by singleApproach #1 : Naive Approach This method is a brute force approach
4 min read
Python | Replace multiple characters at once
The replacement of one character with another is a common problem that every Python programmer would have worked with in the past. But sometimes, we require a simple one-line solution that can perform this particular task. Let's discuss certain ways in which this task can be performed. Method 1: Replace multiple characters using nested replace() Th
6 min read
Python | Multiple indices Replace in String
Sometimes, while working with Python Stings, we can have a problem, in which we need to perform the replace of characters based on several indices of String. This kind of problem can have applications in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop + join() This is brute force way in which this
4 min read
Replace Multiple Lines From A File Using Python
In Python, replacing multiple lines in a file consists of updating specific contents within a text file. This can be done using various modules and their associated functions. In this article, we will explore three different approaches along with the practical implementation of each approach in terms of example code and output. Replace Multiple Lin
3 min read
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 task can be performed. Input : test_str = '* is *
5 min read
Practice Tags :