Censor: Why loop and split? Why not just replace the word instead?


#1

Hi!

I was wondering: When I should just replace a part of a string, why do I have to loop and split the string? Why not just replace the string instead? I tried:

def censor(text, word):
  pixelword = len(word) * '*'
  text.replace(word, pixelword)
  return text

And got:

Your function fails on censor(“hey hey hey”,“hey”). It returns “hey hey hey” when it should return " *".

Any idea why this doesn’t work?


#2

who says the .replace() method isn’t doing that exactly under the hood?

once you successfully wrote your censor function, and you call the function:

censor("hey hey hey", "hey")

look, the function call doesn’t use any loop (even though the actual function might contains loops). This same logic applies to calling replace(). That is why its better to write your own solution/algorithm then using a built-in function, you learn much more from writing your own function

as for why your code is not working, .replace() returns the new string, you don’t store the returned result by .replace() anywhere


#3

as for why your code is not working, .replace() returns the new string, you don’t store the returned result by .replace() anywhere

Ah! That explains a lot. Got it working now. :slight_smile: Thanks for your help.

That is why its better to write your own solution/algorithm then using a built-in function, you learn much more from writing your own function

True! If I compare my code to the method CC suggested in the hint, the .replace()-methdod is much shorter and easier.


#4

true, but you learn less from using a built-in function teaches you far less then building your own algorithm.