0

I am trying to replace a word using re.sub in python. The format is

re.sub(pattern, replacement,string)

Lets consider the following snippet of code

sentence = "I want to replce this sentence"

pattern = "replce"

replacement = "replace"

print(re.sub("[\W]{}[\W]".format(pattern), " {} ".format(replacement), sentence))

Would give output

I want to replace this sentence

Now I want to capture the non-alphanumeric characters around the pattern so that I can include them in the replacement as well. In this example, I am forcing spaces around replacement, which should not be the scenario.

For example

sentence = "I want to !replce, this sentence"

pattern = "replce"

replacement = "replace"

print(re.sub("[\W]{}[\W]".format(pattern), " {} ".format(replacement), sentence))

Would give output

I want to replace this sentence

but I want

I want to !replace, this sentence

What is the solution?

Saurav Mukherjee
  • 177
  • 1
  • 16

0 Answers0