Substitute a part of string (ignoring special characters)

Question:

Suppose that I have a list of strings, and I want to substitute different parts of it by re.sub. My problem is that sometimes this substitution contains special characters inside so this function can’t properly match the structure. One example:

import re

txt = 'May enbd company Ltd (Pty) Ltd, formerly known as apple shop Ltd., is a full service firm which is engaged in the sale and servicing of motor vehicles.'

re.sub('May enbd company Ltd (Pty) Ltd', 'PC (Pty) Ltd', txt)

Here the issue is coming from ( and ), but the other forms may happen that I’m not aware of it now. So I want to totally ignore these special characters inside and replace them with my preferred strings. In this case, it means:

 'PC (Pty) Ltd, formerly known as apple shop Ltd., is a full-service firm which is engaged in the sale and servicing of motor vehicles.'
Asked By: Eghbal

||

Answers:

If no special functionality of regular expressions is needed, this can be done easier with the str.replace method:

txt = 'May enbd company Ltd (Pty) Ltd, formerly known as apple shop Ltd., is a full service firm which is engaged in the sale and servicing of motor vehicles.'

result = txt.replace('May enbd company Ltd (Pty) Ltd', 'PC (Pty) Ltd')
Answered By: Michael Butscher
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.