The question has already been very well answered by Miguel , below is an alternative which handles string indices:
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
The function returns a tuple with the number of occurrences of the word in the string , and the modified text.
Example usage:
texto = "xxxxxxxxxxxxxxx"
# ↑ ↑ ↑ ↑ ↑
# 1 2 3 4 5
print(trocar(texto, "xxx", "AAA", [1, 2])) # (5, 'AAAAAAxxxxxxxxx')
print(trocar(texto, "xxx", "BBB", [2, 3])) # (5, 'xxxBBBBBBxxxxxx')
print(trocar(texto, "xxx", "CCC", [3, 4])) # (5, 'xxxxxxCCCCCCxxx')
print(trocar(texto, "xxx", "DDD", [4, 5])) # (5, 'xxxxxxxxxDDDDDD')
View demonstração
In your case, you can call it like this:
texto = input("Digite o texto: ")
palavra = input("Digite a palavra: ")
cont, trocado = trocar(texto, palavra, "YYY", [3, 5])
print ("{} aparece {} em {}\n".format(palavra, cont, texto))
print (texto)
print (trocado)
# Exemplo de saída
# Digite o texto: foo foo foo foo bar foo
# Digite a palavra: foo
# foo aparece 5 em foo foo foo foo bar foo
# foo foo foo foo bar foo
# foo foo YYY foo bar YYY