python一个一个替换正则表达式匹配的字符
大家都知道怎么用python的re.sub替换所有的字符串,如果是一个一个替换呢?
我提供一个python2的解决方案
import re
def onebyone_replace(string,index):
pattern = re.compile(ur'\d')
if pattern.search(string[index:])==None:
return
else:
start_index,end_index=pattern.search(string[index:]).span()
new_string=pattern.sub('niexinming',string[index:],1)
print string[:index]+new_string
onebyone_replace(string,index+end_index)
onebyone_replace("1-2-3",0)
结果是:
niexinming-2-3
1-niexinming-3
1-2-niexinming
指定位置替换参数
其中appoint_num是指定的位置:
import re
def onebyone_appoint_replace(string,index,num,appoint_num):
pattern = re.compile(ur'\d')
if pattern.search(string[index:])==None:
return
else:
orgin_value=pattern.search(string[index:]).group()
start_index,end_index=pattern.search(string[index:]).span()
new_string=pattern.sub(orgin_value+'niexinming',string[index:],1)
if num==appoint_num: print string[:index]+new_string
num=num+1
onebyone_appoint_replace(string,index+end_index,num,appoint_num)
appoint_number=2
onebyone_appoint_replace("1-2-3",0,0,appoint_number)
结果:
1-2-3niexinming