Python – 随机替换字符串中的单词
给定一个字符串和列表,用列表中的随机元素替换字符串中每个出现的 K 个单词。
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”.
方法#1:使用 shuffle() + loop + replace()
上述功能的组合可以用来解决这个问题。在此,我们使用 replace() 用列表中的随机字符串替换每次出现的 K 个单词。
Python3
# Python3 code to demonstrate working of
# Random Replacement of Word in String
# Using replace() + shuffle() + loop
from random import shuffle
# initializing string
test_str = "Gfg is val. Its also val for geeks"
# printing original string
print("The original string is : " + str(test_str))
# initializing list
repl_list = ["Good", "Better", "Best"]
# initializing replace word
repl_word = "val"
# shuffing list order
shuffle(repl_list)
for ele in repl_list:
# replacing with random string
test_str = test_str.replace(repl_word, ele, 1)
# printing result
print("String after random replacement : " + str(test_str))
Python3
# Python3 code to demonstrate working of
# Random Replacement of Word in String
# Using list comprehension + replace() + shuffle()
from random import shuffle
# initializing string
test_str = "Gfg is val. Its also val for geeks"
# printing original string
print("The original string is : " + str(test_str))
# initializing list
repl_list = ["Good", "Better", "Best"]
# initializing replace word
repl_word = "val"
# one-liner to solve problem
shuffle(repl_list)
res = [test_str.replace(repl_word, ele, 1) for ele in repl_list]
# printing result
print("String after random replacement : " + str(res))
The original string is : Gfg is val. Its also val for geeks
String after random replacement : Gfg is Best. Its also Better for geeks
方法 #2:使用列表推导 + replace() + shuffle()
这是可以执行此任务的方式之一。在此,我们使用与上述方法类似的功能将整个逻辑封装在一行中。
Python3
# Python3 code to demonstrate working of
# Random Replacement of Word in String
# Using list comprehension + replace() + shuffle()
from random import shuffle
# initializing string
test_str = "Gfg is val. Its also val for geeks"
# printing original string
print("The original string is : " + str(test_str))
# initializing list
repl_list = ["Good", "Better", "Best"]
# initializing replace word
repl_word = "val"
# one-liner to solve problem
shuffle(repl_list)
res = [test_str.replace(repl_word, ele, 1) for ele in repl_list]
# printing result
print("String after random replacement : " + str(res))
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’]