1/20 Beginner Projects in Python - Word Replacement

Today is the first day of starting 20 beginner projects series. In this one, we will learn about word replacement in Python.

In this project, we will learn how to replace a word inside the string. We will use function for this project, so that we can use this code as many times as we want.

  • We will start this project by creating a function. As we all know by using function, we can Increase code readabilityand code reusability.

      def replace_word():
    
  • Inside the function, we gonna create a variable name 'sentence' and store string ( "Poem written about Python programming: 'The Zen of Java' ") inside the variable.

  •     sentence = "Poem written about Python programming: 'The Zen of Java'"
    
  • 'word_to_replace' is the variable where we gonna store the word that we want to replace. And for taking input from the user, we will use input function.

      word_to_replace = input("Enter the word to replace: ")
    
  • 'word_replacement' is the variable where we gonna store the replacement word. Use input function to take input from the user.

      word_replacement = input("Enter the word replacement: ")
    
  • Now we going to use replace() method to replace words.

  • The syntax that we will use is: variable.replace()

  • So we will write the variable name where sentence is stored. That is 'sentence' variable. After this we need to use replace() method. sentence.replace() like this. Inside the parenthesis. First we will write the variable where replace word is stored. That is 'word_to_replace' variable, then with comma (,) we will write the variable 'word_replacement' where the replacement word is stored. At last we will store this inside a new variable name new_sentence.

      new_sentence = sentence.replace(word_to_replace, word_replacement)
    
  • At last we need to use print function to print out the new variable.

      print(new_sentence)
    
  • Calling a function is simple. All you need to do is write the name of the function with parenthesis.

      replace_word()
    

    Here is the full code:

  •     def replace_word():
            sentence = "Poem written about Python programming: 'The Zen of Java'"
            word_to_replace = input("Enter the word to replace: ")
            word_replacement= input("Enter the word replacement: ")
            new_sentence = sentence.replace(word_to_replace, word_replacement)
            print(new_sentence)
    

Output of the code:

Thank You for reading this article. I will keep uploading python related content.