Python文本处理

单词替换

单词替换详细操作教程
替换完整的字符串或字符串的一部分是文本处理中非常常见的要求。 replace()方法返回字符串的副本,其中old的出现次数替换为new,可选地将替换次数限制为max。
以下是replace()方法的语法 -
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-23
str.replace(old, new[, max])
old - 这是要替换的旧子字符串。 new - 这是新的子字符串,它将替换旧的子字符串。 max - 如果给出此可选参数max,则仅替换第一次计数出现次数。
此方法返回字符串的副本,子字符串所有出现的old都替换为new。 如果给出了可选参数max,则仅替换第一个计数出现次数。
示例
以下示例显示了replace()方法的用法。
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-23
str = "this is string example....wow!!! this is really string"
print (str.replace("is", "was"))
print (str.replace("is", "was", 3))
当运行上面的程序时,它会产生以下结果 -
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-23
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string
替换忽略大小写
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-23
import re
sourceline = re.compile("Tutor", re.IGNORECASE)
Replacedline = sourceline.sub("Tutor","Tutoriallidihuo has the best tutorials for learning.")
print (Replacedline)
当运行上面的程序时,我们得到以下输出 -
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-23
Tutoriallidihuo has the best Lidihuo for learning.
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4