Replace a special string from a given paragraph with another string in Python

Here, we will see how to replace a special string from a given paragraph with another given string or word in the Python programming language? By Bipin Kumar Last updated : February 25, 2024

Sometimes, we want to replace a string or word of a given paragraph by another string or word and we can do it by editing the paragraph by searching the word but when the length of the paragraph is too large then we feel tired after doing this. So, to overcome this problem we will learn how to do the same things in Python and also we will use the re module of Python to make it so easy.

Replacing a special string from a given paragraph with another string

Python has an inbuilt re module which allows us to solve the various problems based on pattern matching and string manipulation. To understand the problem simply, let's take an example.

Example

Input: 
"These days, Engineers are struggling to get a job in a better company due 
to the lack of experience and also due to the high competition. 
Engineers have the only book knowledge but the company is expecting the 
industrial experience in the Engineers for better productivity."

Replacing:
"Engineers"with "students"

Output: 
"These days, students are struggling to get a job in a better company due 
to the lack of experience and also due to the high competition. 
Students have the only book knowledge but the company is expecting the 
industrial experience in the students for better productivity."

Algorithm

Algorithm to solve the above problem

  1. Import the re module in the program.
  2. Take paragraph as input also a word which uses to replace a special string.
  3. Print the new paragraph which has replaced string.

Program to replace a special string from a given paragraph with another string

# importing the module
import re

# string
paragraph='''These days, Engineers are struggling to get a job in a better 
company due to the lack of experience and also due to the high competition.
Engineers have the only book knowledge but the company is expecting the 
industrial experience in the Engineers for better productivity.'''
# replacing string

reg=re.compile('Engineers')
s=reg.sub("students",paragraph)

# printing the replaced string
print(s)

Output

These days, students are struggling to get a job in a better
company due to the lack of experience and also due to the high competition.
students have the only book knowledge but the company is expecting the
industrial experience in the students for better productivity.

To understand the above program, you should have the basic knowledge of the following Python topics:

Python String Programs »


Related Programs

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.