So. I wrote this code, choosing basically the simplest solution which came to my mind. And it works. (I also played a little adding the option 'What if the word is nit in the string?" and thought I'm quite smart. )
def censor(text, word): replacement = '*' * len(word) if word in text: text = text.replace(word, replacement) return text if word not in text: print "We couldn't find the word." print censor("this hack is wack hack", "hack") print censor("this hack is wack hack", "hag")
Then scrolled through the forum and saw people coming up with solutions using str.split(), like this one below.
def censor(text, word): count = len(word) tear = text.split() new = "" for item in tear: if item == word: new = new +" " + ("*" * count) else: new = new + " " + item sliced = new[1:] return sliced
My question is: are they both fine? I mean, they are both working and you get what you need to get... Is one of them 'better'? And if so, why?
I'm awfully new to programming, so I'd be grateful if someone explained the differences.