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().
The original string is : Gfg is val. Its also val for geeks String after random replacement : Gfg is Best. Its also Better for geeks
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.
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’]
- Python program to read file word by word
- random.random() function in Python
- Random sampling in numpy | random() function
- Switch Case in Python (Replacement)
- Python - Character Replacement Combination
- Find the first repeated word in a string in Python using Dictionary
- Find frequency of each word in a string in Python
- Python | Removing Initial word from string
- Python - Get Nth word in given String
- Python | Replace rear word in String
- Python - Kth word replace in String
- Python program to capitalize the first and last character of each word in a string
- Python - Separate first word from String
- Python | Word location in String
- Python | Generate random string of given length
- Python Program to Generate Random binary string
- Python - Concatenate Random characters in String List
- Count occurrences of a word in string
- Generating random strings until a given string is generated
- Python | Word Similarity using spaCy
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.