FrozenHeart FrozenHeart - 15 days ago 6
Python Question

Replace all the occurrences of specific words

Suppose that I have the following sentence:

bean likes to sell his beans


and I want to replace all occurrences of specific words with other words. For example,
bean
to
robert
and
beans
to
cars
.

I can't just use
str.replace
because in this case it'll change the
beans
to
roberts
.

>>> "bean likes to sell his beans".replace("bean","robert")
'robert likes to sell his roberts'


I need to change the whole words only, not the occurrences of the word in the other word. I think that I can achieve this by using regular expressions but don't know how to do it right.

Answer

If you use regex, you can specify word boundaries with \b:

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'
Comments