Ashton Morgan Ashton Morgan - 1 year ago 130
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.

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)
text = " ".join(text)
return text

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download