需要把下面的str中特殊符号两边添加空格,这里我们都能想到使用查找替换,但是直接使用循环查找替换效率太低下,所以这里想直接使用正则查找来替换,这里难点是如何获取当前匹配到的值是什么,代码如下
import re
str='abc,def,g.h'
patt=re.compile("([,.])")
print re.sub(patt,lambda m:' '+m.group(1)+' ',str)
#output: abc , def , g . h
#done
这里re.sub的第二个参数为:replacement repl.repl can be either a string or a callable,也就是说可以是一个callable传入当前匹配结果为参数的回调函数,理解这个就完成目的了