19
votes

Does "Find-Replace whole word only" exist in python?

e.g. "old string oldstring boldstring bold" if i want to replace 'old' with 'new', new string should look like,

"new string oldstring boldstring bold"

can somebody help me?

2

2 Answers

40
votes
>>> import re
>>> s = "old string oldstring boldstring bold"
>>> re.sub(r'\bold\b', 'new', s)
'new string oldstring boldstring bold'

This is done by using word boundaries. Needless to say, this regex is not Python-specific and is implemented in most regex engines.

5
votes

you need the following regex:

\bold\b