Python Forum

Full Version: Replacing a words' letters in a string
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone, I am a beginner in Python. This is a challenge that I've found in a forum. This program is censoring the words' (which has given by the user) letters with "*" except the first letter. For example, If the sentence is "Every breath you take every move you make" and the input word is "every", the output should look like this:


2 incidents found.
Censored lyrics:
E**** breath you take e**** move you make
This was my only idea but it did not work.
text=input("Enter your text: ").lower()
word=input("Choose a word from the previously entered text: ").lower()
def censor(text,word):
t=text.split()
n=[]
for i in t:
    if(i==word):
        n.append("*"*len(word))
    else:
        n.append(i)
return " ".join(n)
print censor(text,word)
Any help would be appreciated!
Need to indent all code inside a function.

Use i.lower() when testing instead of forcing the entire text to be lower case. You also want to retain the first letter of the censored word.
def censor(text,word):
    t = text.split()
    n = []
    for i in t:
        if(i.lower()==word):
            # Retain first letter if I and append "*"
        else:
            n.append(i)
    return " ".join(n)
Do you also want to return a count? Functions can return more than 1 value.
If censor-word is followed by punctuation (every., every:, every, etc) it will not be censored.