-2

My code works but the problem is that replaces at the wrong places.

Could somepone take a look and better my code.

def find():

    openfile = open(filename, "rt")

    closefile = open(filename, "wt")


    inp1 = input(search)
    inp2 = input(replace)
    for line in fileopen:
        newword = fileout.write(line.replace(inp1, inp2))

    openfile.close()
    closefile.close()
    return newword

find()
coder
  • 19
  • 5
  • simple way - add spaces around, good way - use regex – splash58 Oct 28 '19 at 08:11
  • The issue is that `explain` **does** contain the substring `in`. If you only want to replace a substring if it makes a separate word you do *not* want to use the `str.replace` method but instead use a regex and the `re.sub` function – Giacomo Alzetta Oct 28 '19 at 08:11
  • 1
    @GiacomoAlzetta could you possibly show me how to use it, I am very new to python – coder Oct 28 '19 at 08:13
  • @splash58 could you possibly show me how, in my code I am very knew to python – coder Oct 28 '19 at 08:17

2 Answers2

0

As @splash58 said, the simple way is to add spaces around the word:

newword = line.replace(' ' + searchinput + ' ',' ' + replaceword + ' ')

And the better way is to use regex, meaning add the word boundaries (\b) when searching

import re
newword = re.sub(r'\b{}\b'.format(searchinput),replaceword,line)
ExplodingGayFish
  • 2,807
  • 1
  • 5
  • 14
0

you can use a regex for this! A regex allows you to search for word boundaries as well as specific substrings. You can use the \b identifier for this. This way you know for sure that you pick up only the complete word, and not when it's part of another word.

import re

filterword = input('The word to replace:')
regex = "\\b" +filterword+"\\b"
replacement = input("The word to replace with:")
myString = "I tried to explain in the train."

print(f"Replacing in:\n {myString}")
print(re.sub(regex, replacement, myString))
Kraay89
  • 919
  • 1
  • 7
  • 19