Suppose that I have the following sentence:
bean likes to sell his beans
>>> "bean likes to sell his beans".replace("bean","robert")
'robert likes to sell his roberts'
If you use regex, you can specify word boundaries with
import re sentence = 'bean likes to sell his beans' sentence = re.sub(r'\bbean\b', 'robert', sentence) # 'robert likes to sell his beans'
Here 'beans' is not changed (to 'roberts') because the 's' on the end is not a boundary between words:
\b matches the empty string, but only at the beginning or end of a word.
The second replacement for completeness:
sentence = re.sub(r'\bbeans\b', 'cars', sentence) # 'robert likes to sell his cars'