用Python中的另一个字符串替换给定段落中的特殊字符串
有时,我们想用另一个字符串或单词替换给定段落的字符串或单词,我们可以通过搜索单词来编辑段落来实现,但是当段落的长度太大时,这样做后我们会感到疲倦。因此,为了克服这个问题,我们将学习如何在Python中执行相同的操作,并且还将使用Python的re模块使其变得如此简单。
Python有一个内置的re模块,它使我们能够解决基于模式匹配和字符串操作的各种问题。为了简单地理解问题,让我们举个例子。
示例
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."
解决以上问题的算法
将re模块导入程序中。
以段落作为输入,也是一个用来替换特殊字符串的单词。
打印替换了字符串的新段落。
程序:
# 导入模块
import re
# 字符串
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.'''
# 替换字符串
reg=re.compile('Engineers')
s=reg.sub("students",paragraph)
# 打印替换的字符串print(s)输出结果
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.
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短