Instead of using count, I used the index() formula. My code does not work when there are most than one variable word in the text. I get the error " AttributeError: ‘str’ object has no attribute ‘remove’|’ ‘’
I can find the solution to this issue. Could someone help me ?
Quick question. I was noodling around at the beginning and, yes, I understand I was nowhere near finished, I wanted to test printing to the terminal. However, when printed, it returned additional text. Is this Code Academy being funny?
def censor(text,word):
text = text.split(" ")
for t in text:
print t
censor("help me","no")
My first attempt went immediately to the .replace() function. Reading the FAQ here, i modified my initial code to deal with the “is” trouble in “this”. What I still need to fix is the “This” issue at the beginning of the string, (my code won’t censor words that occur at the start of the string now, because it is looking for a blank in front. But that just gave me an idea. I’ll just add a blank to the front of the string!) I am thinking to grab the first X characters from the string, where X equals len(word to censor). I’m really against using split and join for some reason. I suppose I fear all the additional lines of code will invite a syntax mistake somewhere.
Cheers,
Higrm
def censor(text,word):
if " "+word in text:
return text.replace(" "+word," "+"*"*len(word))
else: return text
print (censor("this hack is wack hack", "is") )
New and improved code now catches words at the start of the string too! I’m sure there are cases where it will fail, but it’s pretty good by my low standards.
def censor(text,word):
if " "+word in " "+text:
return (" "+text).replace(" "+word," "+"*"*len(word))
else: return text
print (censor("this hack is wack hack", "this") )
One final tweak to remove that leading " " I added to get the first word of the string recognized:
def censor(text,word):
if " "+word in " "+text:
return ((" "+text).replace(" "+word," "+"*"*len(word))).strip()
else: return text
print (censor("this hack is wack hack", "this") )
Here’s my code. Seems to me it’s a bit diffrent from what was presented so far (I think). As stetim94 mentioned in one of the post I tried to keep it close to normal English. Decided “result” to be a list not a string: btw “slowo” is “word” in Polish
def censor(text, word):
text_list = text.split( ) #its a list now
result = #creating empty list
stars = “*” * len(word) #how many stars
for slowo in text_list: #for every word in text_list that is a list -
if slowo == word:
slowo = stars #assigning it a new value
else:
slowo = slowo #keeping original value
result.append(slowo) #appending to a list
censored_text = " ".join(result) #list into string
return censored_text