tags:

views:

81

answers:

2

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?

+1  A: 

you need the following regex:

\bold\b
SilentGhost
+7  A: 
>>> 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.

Yuval A