Python – Random Replacement of Word in String
Last Updated :
13 Mar, 2023
Given a string and List, replace each occurrence of K word in string with random element from list.
Input : test_str = “Gfg is x. Its also x for geeks”, repl_list = [“Good”, “Better”, “Best”], repl_word = “x” Output : Gfg is Best. Its also Better for geeks Explanation : x is replaced by random replace list values. Input : test_str = “Gfg is x. Its also x for geeks”, repl_list = [“Good”, “Better”, “Nice”], repl_word = “x” Output : Gfg is Best. Its also Nice for geeks Explanation : x is replaced by random replace list values, “Best” and “Nice”.
Method #1 : Using shuffle() + loop + replace()
The combination of above functions can be used to solve this problem. In this, we replace each occurrence of K word with random string from list using replace().
Python3
from random import shuffle
test_str = "Gfg is val. Its also val for geeks"
print ( "The original string is : " + str (test_str))
repl_list = [ "Good" , "Better" , "Best" ]
repl_word = "val"
shuffle(repl_list)
for ele in repl_list:
test_str = test_str.replace(repl_word, ele, 1 )
print ( "String after random replacement : " + str (test_str))
|
Output
The original string is : Gfg is val. Its also val for geeks
String after random replacement : Gfg is Best. Its also Better for geeks
Time Complexity: O(n*n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n) where n is the number of elements in the list “test_list”.
Method #2 : Using list comprehension + replace() + shuffle()
This is one of the ways in which this task can be performed. In this, we encapsulate entire logic in one-liner using similar functionalities as above method.
Python3
from random import shuffle
test_str = "Gfg is val. Its also val for geeks"
print ( "The original string is : " + str (test_str))
repl_list = [ "Good" , "Better" , "Best" ]
repl_word = "val"
shuffle(repl_list)
res = [test_str.replace(repl_word, ele, 1 ) for ele in repl_list]
print ( "String after random replacement : " + str (res))
|
Output
The original string is : Gfg is val. Its also val for geeks String after random replacement : [‘Gfg is Good. Its also val for geeks’, ‘Gfg is Better. Its also val for geeks’, ‘Gfg is Best. Its also val for geeks’]
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Space Complexity: O(n)
Share your thoughts in the comments
Please Login to comment...