Python Program to replace a word with asterisks in a sentence

In this tutorial, we are going to learn how to replace a word in a word with asterisks in a sentence using Python.

Replacing a word with asterisks in a string

This program is very simple. The idea is as follows:

  • First, split the sentence into words using the split() function in Python.
  • Create a string of asterisks with a length equal to the string that is to be replaced
  • Now, find out the word that is to be replaced in the sentence by traversing through the list.
  • Now replace that string with the string of asterisks.
  • Finally, join all the words into a sentence and print it.
  • If the required word is not there in the given sentence then the given word is invalid.

Here is the code:

sentence = "Replace me with asterisks"
word ="asterisks"
a=sentence.split()
for i in range(len(a)):
    if(a[i]==word):
        a[i]='*'*len(a[i])
print(" ".join(map(str,a)))

If the sentence contains multiple required strings then all of them will be replaced with asterisks of the same length. If you want to change only one string then put a break statement in the if condition.

Leave a Reply

Your email address will not be published. Required fields are marked *