Computer >> Computer tutorials >  >> Programming >> Python

Python Program to replace a word with asterisks in a sentence


We can use a program to replace a word with asterisks in a sentence to censor swear words, etc from a sentence. For example,

If we have a sentence,

"Go feed all the ducks in the lake"

And a word that we want to replace with asterisks, let's say ducks. Then our final sentence will look like −

"Go feed all the ***** in the lake"

We can directly use the replace function from python to achieve this functionality. For example,

Example

def replaceWithAsterisk(sent, word):
# Use the replace function to find and replace the word with
# same number of asterisks as the length of the word.
return sent.replace(word, "*" * len(word))

sent = "Go feed all the ducks in the lake"
censored_sent = replaceWithAsterisk(sent, "ducks")

print(censored_sent)

Output

This will give the output −

Go feed all the ***** in the lake