Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace exact substring in python [duplicate]

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?

like image 657
Animesh Sharma Avatar asked Jul 29 '15 09:07

Animesh Sharma


People also ask

How do you replace only one occurrence of a string in Python?

>>> 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.

How do you replace a repeated character in a string in Python?

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.

How do you replace and match in Python?

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.


1 Answers

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.

like image 85
falsetru Avatar answered Sep 25 '22 02:09

falsetru