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?
>>> help(str. replace) Help on method_descriptor: replace(...) S. replace (old, new[, count]) -> string Return a copy of string S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
replace() to Replace Multiple Characters in Python. We can use the replace() method of the str data type to replace substrings into a different output.
To replace a string in Python, the regex sub() method is used. It is a built-in Python method in re module that returns replaced string. Don't forget to import the re module. This method searches the pattern in the string and then replace it with a new given expression.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With