re.sub用于替换字符串中的匹配项。
re.sub的函数原型为:re.sub(pattern, repl, string, count)
1. Example1:将字符串中的空格 ' ' 替换成 '_' :
import re
text = "osc ring efuse info"
print re.sub(r'\s+', '_', text)
# 输出结果:
"osc_ring_efuse_info"
2.Example1:将字符串中的空格 ' ' 给去掉 :
import re
text = "am_ring_osc_clk_out_ee[0] :1859 KHz"
print re.sub(r'\s+', '', text)
输出结果:
"am_ring_osc_clk_out_ee[0]:1859KHz"
其中第二个函数是替换后的字符串;本例中为'_'或者''
第四个参数指替换个数。默认为0,表示每个匹配项都替换。
re.sub还允许使用函数对匹配项的替换进行复杂的处理。如:re.sub(r'\s', lambda m: '[' + m.group(0) + ']', text, 0);将字符串中的空格' '替换为'[ ]'。