0

I am trying to replace some text in a string. I have "Microsoft Inc." and I want to replace it as "Microsoft Incorporation". For this I have tried like

company = 'Microsoft Inc.'
key = 'Inc.'
pattern = r'\b' + key + r'\b'
# pattern = r'\b' + re.escape(key) + r'\b'
_change = 'Incorporation'
y = re.sub(pattern, _change, company)
print(y)

I dont see any replacements. but when I remove "." from company and key then it is working fine, but when there is "." in string it doesnt change any thing.

Raady
  • 1,686
  • 5
  • 22
  • 46
  • 2
    First of all, escape variables, `re.escape(key)`. Second, do not use `\b` if you have special chars at the start/end of words, use `(?<!\w)` / `(?!\w)` or `(?<!\S)` / `(?!\S)` custom boundaries. – Wiktor Stribiżew Apr 03 '20 at 12:26
  • thank you @Wiktor Stribizew: it worked ! – Raady Apr 03 '20 at 12:32

0 Answers0