##replace函数,跟split函数处理类似,比split简单 #coding=gbk ss='** *axx* *bv** *ctt** **dff***' print(ss) result=[] def replace_1(s,a,dd,times=None): i=0 n=0 #记录替换次数,对应判断times result=[] if times==None: times=len(s) while i<len(s) and len(s)!=0 and n<times: if s[i:i+len(a)]==a: result+=list(s[0:i])+list(dd) s=s[i+len(a):] n+=1 i=0 else: i+=1 result.append(s) return ''.join(result) print('替换后的结果为:',replace_1(ss,' ','hhh'))