0

I have a sentence as follows:

s="This is my cat who is my ally and this is my dog who has started to finally act like one."

I want to replace certain words in the sentence with other words. Example:

cat with bat, ally with protector.

Now the problem occurs with similar words. For example ally and finally

s="This is my cat who is my ally and this is my dog who has started to finally act like one."
for r in (("cat", "bat"),("ally", "protector")):
    s = s.replace(*r)
print(s)

This should give me:

This is my bat who is my protector and this is my dog who has started to finally act like one.

But it gives me the following output affecting finally because of ally:

This is my bat who is my protector and this is my dog who has started to finprotector act like one.

It affects finally and converts it to finprotector. I don't want this. How can I solve this issue? Any help will be appreciated.

Reema Q Khan
  • 878
  • 1
  • 7
  • 20

3 Answers3

2

You can include spaces in your replace to only select individual words.

s="This is my cat who is my ally and this is my dog who has started to finally act like one."
for r in ((" cat ", " bat "),(" ally ", " protector ")):
    s = s.replace(*r)
print(s)
This is my bat who is my protector and this is my dog who has started to finally act like one.
Mitchell Olislagers
  • 1,758
  • 1
  • 4
  • 10
2

Use regular expressions with a dictionary, re.sub , and lambda like so:

import re

s = "This is my cat who is my ally and this is my dog who has started to finally act like one."
dct = {
    'cat': 'bat',
    'ally': 'protector'
}

regex = re.compile(r'\b(' + '|'.join(map(re.escape, dct.keys())) + r')\b')
print(regex.sub(lambda match: dct[match.group(0)], s))
# This is my bat who is my protector and this is my dog who has started to finally act like one.

Note that \b denotes word break, which allows ally and , ally , but not finally, to be matched.

Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
1

Maybe you want to try the regular expressions and the re module (particulary the re.sub() method)?

import re

line = re.sub(r'\bally\b', 'protector', s)
Roman Zh.
  • 985
  • 2
  • 6
  • 20
  • How to give more than one condition like cat->bat, ally->protector .... – Reema Q Khan Jan 15 '21 at 13:53
  • 1
    I would say several calls of the `re.sub`. Take into account that the method has an optional argument `count`: by default, it changes only the leftmost appearance of the replacing pattern. – Roman Zh. Jan 15 '21 at 13:55