0

I have a problem in a "Search and Replace" homework in Python. I've done the replacements and displayed how many words are replaced. But other words are mistakenly replaced for example. Search: ART, Replace: ARTS, somehow other words like TART, FART, etc. are also replaced into TARTS.


search_text = input("Enter word to search: ")
replace_text = input("Enter new word: ")

with open('words.txt', 'r+') as file:
    data = file.read()
        
    data = data.replace(search_text,replace_text)
    instances = data.count(replace_text)

    file.write(data)
    file.close()
#with open(r'words.txt', 'w') as file:
    #file.truncate(0)
    #file.write(data)
    #file.close()
    
print("Word(s) replaced",instances)

0 Answers0