Reputation: 115
How am I supposed to replace an exact word from a sentence in python. I used the .replace() function but it replaces the word also if it is a part of word, for example "he is missing" and i replace "is", the output is "he msing". I tried inserting spaces before and after the word to be matched, but then it can't remove the word if it is at beginning of sentence, also if it is followed by a punctuation mark then also. I am thinking it can be done by regular expression but can't think of doing so.Is there any other way also, please tell me
Upvotes: 4
Views: 1918
Reputation: 213115
Use the word boundaries \b
to mark the place between an alphanumerical character and any other character:
newString = re.sub(r'\boldword\b', r'newword', oldString)
Upvotes: 7