def inv_replace(x, y, delim=", "):
pre = delim if y.index(x) else ""
post = delim if y.rindex(x) + len(x) != len(y) else ""
return pre + delim.join([x] * y.count(x)) + post
s = "foo bar foobar bar foocar foo"
sl = s.split(" ") #put all words in a list
for i in range(len(sl)):
word = sl[i]
if not word == "bar":
sl[i] = "newtext" #make the word into "newtext", and replace it in the list
s = sl.join(" ") #put the words back in the string
像这样:
编辑问题之前获取
", String, String, "
类答案:如果您只是想替换字符串中的单词,只需检查每个单词,如果它不等于要保护的单词,则可以替换它,如下所示:
输出:
相关问题 更多 >
编程相关推荐