Python - 替换给定单词以外的所有单词
给定一个字符串。任务是用“?”替换所有单词。除了给定的单词 K。
例子:
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 : All words except gfg is replaced by ?.
方法 #1:使用 split() + join() + 循环
这是可以执行此任务的粗暴方式。在此,我们使用 split() 执行将字符串更改为单词列表的任务,然后检查 K 个单词,如果未找到,则将其替换为适当的值。最后,使用 join() 转换回字符串。
Python3
# Python3 code to demonstrate working of
# Replace all words not K
# Using join() + split() + loop
# initializing string
test_str = 'gfg is best for geeks gfg is for cs I love gfg'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = "gfg"
# initializing repl_char
repl_char = "?"
# extracting words
temp = test_str.split(" ")
for idx in range(len(temp)):
ele = temp[idx]
# replace non K with repl_char
if not ele == K:
temp[idx] = repl_char
# joining result
res = " ".join(temp)
# printing result
print("The resultant string : " + str(res))
Python3
# Python3 code to demonstrate working of
# Replace all words not K
# Using list comprehension
# initializing string
test_str = 'gfg is best for geeks gfg is for cs I love gfg'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = "gfg"
# initializing repl_char
repl_char = "?"
# using one-liner to solve this problem
res = " ".join(
[repl_char if not ele == K else ele for ele in test_str.split()])
# printing result
print("The resultant string : " + str(res))
输出:
The original string is : gfg is best for geeks gfg is for cs I love gfg
The resultant string : gfg ? ? ? ? gfg ? ? ? ? ? gfg
方法#2:使用列表理解
这是可以执行此任务的另一种方式。在这种情况下,我们迭代元素并使用与上述方法类似的功能使用 one-liner 执行任务。
蟒蛇3
# Python3 code to demonstrate working of
# Replace all words not K
# Using list comprehension
# initializing string
test_str = 'gfg is best for geeks gfg is for cs I love gfg'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = "gfg"
# initializing repl_char
repl_char = "?"
# using one-liner to solve this problem
res = " ".join(
[repl_char if not ele == K else ele for ele in test_str.split()])
# printing result
print("The resultant string : " + str(res))
输出:
The original string is : gfg is best for geeks gfg is for cs I love gfg
The resultant string : gfg ? ? ? ? gfg ? ? ? ? ? gfg