Python implements a method that finds matches for processing and replaces them back
- 2020-06-03 07:05:16
This article illustrates the Python implementation of finding matches, processing them, and then replacing them back. To share for your reference, specific as follows:
Python is implemented here to replace the original match after processing the found match appropriately.
#!/usr/bin/python # coding=GBK import re # right m The result is returned after proper processing def fun(m): print("in: %s" %m.group(0)) ret = m.group(0).upper()[::-1] return ret src = "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 lambda result1 = re.sub(pat, lambda m:m.group(0).upper()[::-1], src) print("result1: %s\n" %result1) # in re.sub Functions used in result2 = re.sub(pat, fun, src) print("result2: %s" %result2)
[zcm@python #112]$./del.py result1: what [NAC] I do for can you[NAC] come on in: can in: can result2: what [NAC] I do for can you[NAC] come on [zcm@python #113]$
See, everything that matches "[can]" has been "capitalized and inverted".
For more information about Python, please refer to Python String Manipulation Skills summary, Python Common Traversal Skills Summary, Python Data Structure and Algorithm Tutorial, Python Functions Summary and Python Introduction and Advanced Classic Tutorial.
I hope this article has been helpful in Python programming.