Python finds matching items for processing and then replaces them
This example describes how to search for matching items in Python and then replace them. We will share this with you for your reference. The details are as follows:
Here, Python can properly process the matched items found and then replace the original matching items.
#! /Usr/bin/python # coding = GBKimport re # returns the result 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) # Use lambdaresult1 = re. sub (pat, lambda m: m. group (0 ). upper () [:-1], src) print ("result1: % s \ n" % result1) # In re. use the result2 = re. sub (pat, fun, src) print ("result2: % s" % result2)
Running output:
[Zcm @ python #112] $. /del. pyresult1: what [NAC] I do for you [NAC] come onin: canin: canresult2: what [NAC] I do for you [NAC] come on [zcm @ python #113] $
Have you seen that all the items that match "[can]" are "converted to uppercase and inverse.