3
I have a long string inside a txt file, for example, let’s say my string is about that:
strg = '123456 BANANA 00 SP'
In position 14 and 15 we have the "00"
, I’m gonna need to replace up front
The logic I’m implementing is:
import re
#abre e começa a leitura do arquivo
arquivo = open('teste.txt','r')
conteudo = arquivo.read()
#verifica se existe a palavra BANANA
if re.search('\\bBANANA\\b', conteudo, re.IGNORECASE):
print("ACHOU")
encontrado = True
else:
print("NÃO ACHOU")
encontrado = False
#caso o retorno acima seja true, ele substitui a posição 14 e 15 pela string "22"
if encontrado:
splt = conteudo.replace(14:15, "22") #o que eu esperava, mas não funciona!
print(splt)
arquivo = open('teste.txt', 'w')
arquivo.writelines(conteudo)
arquivo.close()
When I get to the part of giving the replace
in positions 14:15 by "22", I cannot do, because apparently the method replace
just compare the strings and replace it, and that wouldn’t work for me, because on the same line I can have several "00" and it would replace all by "22", but I need it to change only that specific position, it doesn’t guide by a string.
What better way for me to do that replace
from a specific position in the string?