您可以re.search
使用re.sub
.
def count_sub(pattern,text,repl=''):
count=1
while re.search(pattern,text):
text=re.sub(pattern,repl+str(count),text,count=1)
count+=1
return text
输出:
count_sub(r'o', 'oh hello world')
# '1h hell2 w3rld'
count_sub(r'o', 'oh hello world','a')
# 'a1h hella2 wa3rld'
选择:
def count_sub1(pattern,text,repl=''):
it=enumerate(re.finditer(pattern,text),1)
count=1
while count:
count,_=next(it,(0,0))
text=re.sub(pattern,repl+str(count),text,count=1)
return text
输出:
count_sub1(r'o','oh hello world')
# '1h hell2 w3rld'
count_sub1(r'o','oh hello world','a')
# 'a1h hella2 wa3rld'