How to replace a word in a sentence without using the python replace method

i have written a function to replace a word in a sentence without using the python built in replace method, the issue is that my code fails in edge cases were the word combines with another, am suppose to replace every occurrence of maybe with perhaps. Take a look at my code

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)

the output is:

Perhaps she's born with it. Perhaps it's Maybeline.

But am expecting it to print this:

Perhaps she's born with it. Perhaps it's perhapsline. 

Notice the last word which is maybeline is suppose to change to perhapsline. I have battled with this for a week now, any help will be appreciated.

Upvotes: 1

Views: 3252

Answers (1)

MatsLindh
MatsLindh

Reputation: 52912

The reason is that you're splitting on whitespace, so when you're comparing i to find, you're comparing Maybeline. to Maybe. That won't match, so you're not replacing that occurrence.

If you split by the value you're looking for instead, and then join the parts with the replacement string, you'll get a number of strings, split where Maybe used to be, and you can join these with the replace string between them:

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.

Upvotes: 3

Related Questions