4

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

1 Answer 1

7

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.