def replace_all (target,find,replace):
split_target = target.split()
result = ''
for i in split_target:
if i == find:
i = replace
result += i + ' '
return result.strip()
target = "Maybe she's born with it. Maybe it's Maybeline."
find = "Maybe"
replace = "Perhaps"
print replace_all(target, find, replace)
输出是:
Perhaps she's born with it. Perhaps it's Maybeline.
但我希望它打印出来:
Perhaps she's born with it. Perhaps it's perhapsline.
注意最后一个单词是maybeline,假设改为norline。我已经与这场斗争了一个星期了,任何帮助都将受到赞赏。
答案 0 :(得分:3)
原因是您正在拆分空格,所以当您将i
与find
进行比较时,您将Maybeline.
与Maybe
进行比较。那将不匹配,所以你不会取代那个事件。
如果你按照你正在寻找的值拆分,然后用替换字符串连接部分,你会得到一些字符串,在使用Maybe
的地方分开是的,你可以加入它们之间的replace
字符串:
def replace_all (target,find,replace):
return replace.join(target.split(find))
target = "Maybe she's born with it. Maybe it's Maybeline."
find = "Maybe"
replace = "Perhaps"
print(replace_all(target, find, replace))
> Perhaps she's born with it. Perhaps it's Perhapsline.