Python – 不区分大小写的字符串替换
给定字符串单词。任务是编写一个Python程序,用给定的字符串替换给定的单词,而不管大小写。
例子:
Input : test_str = “gfg is BeSt”, repl = “good”, subs = “best”
Output : gfg is good
Explanation : BeSt is replaced by “good” ignoring cases.
Input : test_str = “gfg is BeSt”, repl = “better”, subs = “best”
Output : gfg is better
Explanation : BeSt is replaced by “better” ignoring cases.
方法 #1:使用 re.IGNORECASE + re.escape() + re.sub()
在此,正则表达式的 sub() 用于执行替换和 IGNORECASE 任务,忽略大小写并执行不区分大小写的替换。
Python3
# Python3 code to demonstrate working of
# Case insensitive Replace
# Using re.IGNORECASE + re.escape() + re.sub()
import re
# initializing string
test_str = "gfg is BeSt"
# printing original string
print("The original string is : " + str(test_str))
# initializing replace string
repl = "good"
# initializing substring to be replaced
subs = "best"
# re.IGNORECASE ignoring cases
# compilation step to escape the word for all cases
compiled = re.compile(re.escape(subs), re.IGNORECASE)
res = compiled.sub(repl, test_str)
# printing result
print("Replaced String : " + str(res))
Python3
# Python3 code to demonstrate working of
# Case insensitive Replace
# Using sub() + lambda + escape()
import re
# initializing string
test_str = "gfg is BeSt"
# printing original string
print("The original string is : " + str(test_str))
# initializing replace string
repl = "good"
# initializing substring to be replaced
subs = "best"
# regex used for ignoring cases
res = re.sub('(?i)'+re.escape(subs), lambda m: repl, test_str)
# printing result
print("Replaced String : " + str(res))
输出
The original string is : gfg is BeSt
Replaced String : gfg is good
方法 #2:使用 sub() + lambda + escape()
使用特定的忽略大小写正则表达式也可以解决这个问题。休息一下,如果字符串存在转义字符,则使用 lambda函数来处理转义字符。
蟒蛇3
# Python3 code to demonstrate working of
# Case insensitive Replace
# Using sub() + lambda + escape()
import re
# initializing string
test_str = "gfg is BeSt"
# printing original string
print("The original string is : " + str(test_str))
# initializing replace string
repl = "good"
# initializing substring to be replaced
subs = "best"
# regex used for ignoring cases
res = re.sub('(?i)'+re.escape(subs), lambda m: repl, test_str)
# printing result
print("Replaced String : " + str(res))
输出
The original string is : gfg is BeSt
Replaced String : gfg is good