The question was already very good answered by Miguel, follows below an alternative manipulating the indices of the string:
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 string, and the modified text.
Example of use:
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')
See demonstração
In your case, you can call her that:
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
A question wants to change the word when it repeats in the string for the third/fifth time, in the same/only in the place where the right third or fifth occurrence was found?
– Miguel
only on the 3 and 5 times, and no other.
– Adriano Brito