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