本文實例講述了Python實現查找匹配項作處理后再替換回去的方法。分享給大家供大家參考,具體如下:
這里實現Python在對找到的匹配項進行適當處理后,再替換掉原來那個匹配的項。
#!/usr/bin/python# coding=GBKimport re# 對m作適當處理后返回結果def fun(m): print("in: %s" %m.group(0)) ret = m.group(0).upper()[::-1] return retsrc = "what [can] I do for can you[can] come on"pat = "(?<=)(can)(?=)"#print(re.search(pat, src).group(1))#result = re.sub(pat,lambda m:m.group(1).upper()[::-1], src)# 使用lambdaresult1 = re.sub(pat, lambda m:m.group(0).upper()[::-1], src)print("result1: %s/n" %result1)# 在re.sub中使用函數result2 = re.sub(pat, fun, src)print("result2: %s" %result2)運行輸出:
[zcm@python #112]$./del.pyresult1: what [NAC] I do for can you[NAC] come onin: canin: canresult2: what [NAC] I do for can you[NAC] come on[zcm@python #113]$
看到了嗎,所有匹配"[can]"的項都被“轉換成大寫并逆順”了。
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答