python re.I compile search

import re
string = "The quick brown fox jumps over the lazy dog."
a_list = string.split()
pattern = re.compile(r'THE',re.I)

count = 0
for word in a_list:
if pattern.search(word):
count +=1
print(count)

替换方式1

string_to_find = r"the"
pattern = re.compile(string_to_find,re.I)
print(re.sub(pattern,"a",string))

替换方式2

string_to_find = r"the"
pattern = re.compile(string_to_find,re.I)
print(pattern.sub("a",string))

re.sub索引替换作用,替换方式1和替换方式2的作用是一样的。

原文地址:https://www.cnblogs.com/shida-liu/p/10077275.html