Python – Replace multiple words with K
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 stringtest_str = 'Geeksforgeeks is best for geeks and CS'# printing original stringprint("The original string is : " + str(test_str))# initializing word listword_list = ["best", 'CS', 'for']# initializing replace wordrepl_wrd = 'gfg'# Replace multiple words with K# Using join() + split() + list comprehensionres = ' '.join([repl_wrd if idx in word_list else idx for idx in test_str.split()])# printing resultprint("String after multiple replace : " + str(res)) |
The original string is : Geeksforgeeks is best for geeks and CS String after multiple replace : Geeksforgeeks is gfg gfg geeks and gfg
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 stringtest_str = 'Geeksforgeeks is best for geeks and CS'# printing original stringprint("The original string is : " + str(test_str))# initializing word listword_list = ["best", 'CS', 'for']# initializing replace wordrepl_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 resultprint("String after multiple replace : " + str(res)) |
The original string is : Geeksforgeeks is best for geeks and CS String after multiple replace : Geeksforgeeks is gfg gfg geeks and gfg
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Auxiliary Space: O(n)


