📜  Python – 字符串中的第 K 个单词替换

📅  最后修改于: 2022-05-13 01:54:51.594000             🧑  作者: Mango

Python – 字符串中的第 K 个单词替换

有时,在使用 String list 时,我们可能会遇到需要替换字符串的第 K 个单词的问题。这个问题在Web开发领域有很多应用。让我们讨论一种可以解决这个问题的方法。

方法:使用split() + join()
这是我们可以执行此任务的方式。在此,我们将元素分成几部分,然后返回第 K 个值并使用 join() 执行添加新元素。

# Python3 code to demonstrate working of
# Kth word replace in String
# using split() + join()
  
# initializing string 
test_str = "GFG is good"
  
# printing original string 
print("The original string is : " + test_str)
  
# initializing replace string 
rep_str = "best"
  
# initializing K 
K = 1 
  
# Kth word replace in String
# using split() + join()
temp = test_str.split(' ')
res = " ".join(temp[: K]  + [rep_str] + temp[K + 1 :])
  
# printing result
print("The String after performing replace : " + res)
输出 :
The original string is : GFG is good
The String after performing replace : GFG best good