fork download
  1. def trocar (texto, substituir, substituto, ocorrencias):
  2. indice = texto.find(substituir)
  3. cont = texto.count(substituir)
  4. ret = texto
  5. n = 1
  6.  
  7. while indice >= 0 and n <= cont:
  8. if n in ocorrencias:
  9. ret = ret[:indice] + substituto + ret[len(substituir) + indice:]
  10. indice = ret.find(substituir, indice + len(substituto))
  11. n += 1
  12.  
  13. return cont, ret
  14.  
  15.  
  16. texto = "xxxxxxxxxxxxxxx"
  17.  
  18. print(trocar(texto, "xxx", "AAA", [1, 2]))
  19. print(trocar(texto, "xxx", "BBB", [2, 3]))
  20. print(trocar(texto, "xxx", "CCC", [3, 4]))
  21. print(trocar(texto, "xxx", "DDD", [4, 5]))
Success #stdin #stdout 0.01s 9992KB
stdin
Standard input is empty
stdout
(5, 'AAAAAAxxxxxxxxx')
(5, 'xxxBBBBBBxxxxxx')
(5, 'xxxxxxCCCCCCxxx')
(5, 'xxxxxxxxxDDDDDD')