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.

1
  • 1
    Use regex. re.sub('\bally\b', 'protector', s) Commented Jan 15, 2021 at 13:47

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

Wow! Thanks a lot buddy. :D You saved the day.
This will however not work if the string is my cat, who is my ally which would make more grammatical sense. You should use Regular-Expression here ideally.
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)

2 Comments

How to give more than one condition like cat->bat, ally->protector ....
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.