标签:case pre api 匹配 字符串 ret replace code upper
import re
text = 'UPPER PYTHON, lower python, Mixed Python'
f = re.findall("python", text, flags=re.IGNORECASE)
print(f)
s, n = re.subn("python","snake",text, flags=re.IGNORECASE)
print(s)
print(n) # 返回匹配的次数
替换之后的字符串与被替换的大小写不能保持一致
def matchcase(word):
def replace(m): # 匹配的结果 如:PYTHON
text = m.group()
if text.isupper():
return word.upper()
elif text.islower():
return word.lower()
elif text[0].isupper():
return word.capitalize()
else:
return word
return replace
if __name__ == '__main__':
s = re.sub('python', matchcase('snake'), text, flags=re.IGNORECASE)
print(s)
标签:case pre api 匹配 字符串 ret replace code upper
原文地址:https://www.cnblogs.com/action-go/p/11801641.html