Python implements a method that finds matches for processing and replaces them back

  • 2020-06-03 07:05:16
  • OfStack

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.

# coding=GBK
import re
#  right m The result is returned after proper processing 
def fun(m):
  print("in: %s"
  ret =[::-1]
  return ret
src = "what [can] I do for can you[can] come on"
pat = "(?<=
#print(, src).group(1))
#result = re.sub(pat,lambda[::-1], src)
#  use lambda
result1 = re.sub(pat, lambda[::-1], src)
print("result1: %s\n" %result1)
#  in re.sub Functions used in 
result2 = re.sub(pat, fun, src)
print("result2: %s" %result2)

Operation output:

[zcm@python #112]$./
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.

Related articles: