def myReplace(s,sub, dest, times =None): #如果times是None,替换的次数是s.count(sub) if times == None: times = s.count(sub) sub_index = [] sub_length = len(sub) dest_length = len(dest) s = list(s) for i in range(len(s)): if s[i:i+sub_length] == list(sub): sub_index.append(i) n = 0 for index in sub_index: if times > 0: offset = n * (dest_length - sub_length) index = index + offset s[index:index+sub_length] = list(dest) n += 1 times -= 1 return "".join(s) print(myReplace("abcc1aha",'a','xy')) print(myReplace("abcdefgabca","a","123",1))