Ashton Morgan Ashton Morgan - 1 month ago 11
Python Question

Python newbie - refactor string function

I started learning Python yesterday and one of the challenges on the site I am using is asking to solve this problem below. While I did solve the problem successfully it looks very amateurish and I would like if someone smart could show a better solution or offer any related advice. Thanks.

Problem:
Write a function called censor that takes two strings, text and word, as input. It should return the text with the word you chose replaced with asterisks.

My Solution:

def censor(text, word):
text = text.split(" ")
for i in text:
if i == word:
i_index = text.index(i)
i = "*" * len(i)
del(text[i_index])
text.insert(i_index,i)
text = " ".join(text)
return text

Answer
def censor(text, word):
    return text.replace(word, '*')

Simple string replace function, pretty much found in any standard library.

Comments