Tutorialspoint.dev

Program to replace a word with asterisks in a sentence

For the given sentence as input, censor a specific word with asterisks ‘ * ‘.

Example :

Input : word = “computer”
text = “GeeksforGeeks is a computer science portal for geeks. People who love computer and computer codes can contribute their valuables/ideas on computer codes/structures on here.”
Output : GeeksforGeeks is a ******** science portal for geeks. People who love ******** and ******** codes can contribute their valuables/ideas on ******** codes/structures on here.



The idea is to first split given sentence into different words. Then traverse the word list. For every word in the word list, check if it matches with given word. If yes, then replace the word with stars in the list. Finally merge the words of list and print.

Python3

# Python Program to censor a word
# with asterisks in a sentence
  
  
# Function takes two parameter
def censor(text, word):
  
    # Break down sentence by ' ' spaces
    # and store each individual word in
    # a different list
    word_list = text.split()
  
    # A new string to store the result
    result = ''
  
    # Creating the censor which is an asterisks 
    # "*" text of the length of censor word
    stars = '*' * len(word)
  
    # count variable to 
    # access our word_list
    count = 0
  
    # Iterating through our list
    # of extracted words
    index = 0;
    for i in word_list:
  
        if i == word:
              
            # changing the censored word to 
            # created asterisks censor
            word_list[index] = stars
        index += 1
  
    # join the words
    result =' '.join(word_list)
  
    return result
  
# Driver code
if __name__== '__main__':
      
    extract = "GeeksforGeeks is a computer science portal for geeks.
               I am pursuing my major in computer science. "               
    cen = "computer"    
    print(censor(extract, cen))

PHP


Output :

GeeksforGeeks is a ******** science portal for geeks.
I am pursuing my major in ******** science.


This article is attributed to GeeksforGeeks.org

You Might Also Like

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter