def trocar (texto, substituir, substituto, ocorrencias):
indice = texto.find(substituir)
cont = texto.count(substituir)
ret = texto
n = 1
while indice >= 0 and n <= cont:
if n in ocorrencias:
ret = ret[:indice] + substituto + ret[len(substituir) + indice:]
indice = ret.find(substituir, indice + len(substituto))
n += 1
return cont, ret
texto = "xxxxxxxxxxxxxxx"
print(trocar(texto, "xxx", "AAA", [1, 2]))
print(trocar(texto, "xxx", "BBB", [2, 3]))
print(trocar(texto, "xxx", "CCC", [3, 4]))
print(trocar(texto, "xxx", "DDD", [4, 5]))
ZGVmIHRyb2NhciAodGV4dG8sIHN1YnN0aXR1aXIsIHN1YnN0aXR1dG8sIG9jb3JyZW5jaWFzKToKCWluZGljZSA9IHRleHRvLmZpbmQoc3Vic3RpdHVpcikKCWNvbnQgPSB0ZXh0by5jb3VudChzdWJzdGl0dWlyKQoJcmV0ID0gdGV4dG8KCW4gPSAxCgkKCXdoaWxlIGluZGljZSA+PSAwIGFuZCBuIDw9IGNvbnQ6CgkJaWYgbiBpbiBvY29ycmVuY2lhczoKCQkJcmV0ID0gcmV0WzppbmRpY2VdICsgc3Vic3RpdHV0byArIHJldFtsZW4oc3Vic3RpdHVpcikgKyBpbmRpY2U6XSAgICAgICAgCgkJaW5kaWNlID0gcmV0LmZpbmQoc3Vic3RpdHVpciwgaW5kaWNlICsgbGVuKHN1YnN0aXR1dG8pKQoJCW4gKz0gMQoJCglyZXR1cm4gY29udCwgcmV0CgoKdGV4dG8gPSAieHh4eHh4eHh4eHh4eHh4IgoKcHJpbnQodHJvY2FyKHRleHRvLCAieHh4IiwgIkFBQSIsIFsxLCAyXSkpCnByaW50KHRyb2Nhcih0ZXh0bywgInh4eCIsICJCQkIiLCBbMiwgM10pKQpwcmludCh0cm9jYXIodGV4dG8sICJ4eHgiLCAiQ0NDIiwgWzMsIDRdKSkKcHJpbnQodHJvY2FyKHRleHRvLCAieHh4IiwgIkRERCIsIFs0LCA1XSkp