如何在不使用python替换方法的情况下替换句子中的单词

时间:2017-10-15 21:13:34

标签: python

我已经编写了一个函数来替换一个单词而不使用python内置的替换方法,问题是我的代码在边缘情况下失败了这个单词与另一个单词结合,我想更换每一个可能与也许。看看我的代码

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。我已经与这场斗争了一个星期了,任何帮助都将受到赞赏。

1 个答案:

答案 0 :(得分:3)

原因是您正在拆分空格,所以当您将ifind进行比较时,您将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.