用Python中的另一个字符串替换给定段落中的特殊字符串

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.

有时,我们想用另一个字符串或单词替换给定段落的字符串或单词 ,我们可以通过搜索单词来编辑段落来实现,但是当段落的长度太大时,这样做后我们会感到疲倦。 因此,为克​​服此问题,我们将学习如何在Python中执行相同的操作,并且还将使用Pythonre模块使其变得如此简单。

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.

Python有一个内置的re模块 ,它使我们能够解决基于模式匹配和字符串操作的各种问题。 为了简单地理解问题,让我们举个例子。

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 to solve the above problem

解决以上问题的算法

  1. Import the re module in the program.

    re模块导入程序中。

  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:

程序:

# 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.


翻译自: https://www.includehelp.com/python/replace-a-special-string-from-a-given-paragraph-with-another-string.aspx

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值