16

Example string: "office administration in delhi"

I want to replace in from the string with a blank. But when I do, s.replace('in',""), the in of administration also becomes blank.

This is just a sample. The string and the word to replace may vary.

Is there some way to replace only the exact match?

Animesh Sharma
  • 3,258
  • 1
  • 17
  • 33

1 Answers1

37

You can use regular expression \bin\b. \b here means word boundary. \bin\b will match in surrounded by word boundary (space, punctuation, ...), not in in other words.

>>> import re
>>> re.sub(r'\bin\b', '', 'office administration in delhi')
'office administration  delhi'

See re.sub.

falsetru
  • 357,413
  • 63
  • 732
  • 636