Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Substitute a part of string (ignoring special characters)

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.'

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading