本文實例講述了Python實現(xiàn)查找匹配項作處理后再替換回去的方法。分享給大家供大家參考,具體如下:
這里實現(xiàn)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中使用函數(shù)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相關內容可查看本站專題:《Python字符串操作技巧匯總》、《Python常用遍歷技巧總結》、《Python數(shù)據(jù)結構與算法教程》、《Python函數(shù)使用技巧總結》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答