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

How to replace an exact word match in Python

I am trying to automate some part of my work using Python script in which I have to replace a set of words from dbt scripts.

So first of all I have a list of those substrings that need to be replaced with some other values.

A = ['{{FIRST_STRING}}','{{SECOND_STRING}}','{{THIRD_STRING}}']

The Curly brackets are the part of string. Now I have my actual string in below manner

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

ACTUAL_STRING = """My first String is {{FIRST_STRING}}, 
My second String is {{SECOND_STRING}} 
and third string is {{THIRD_STRING}} """

Now I want to perform some replace operations in ACTUAL_STRING in such a way that I can get below string

EXPECTED_STRING = 'My first String is A, 
My second String is B
and third string is C' 

I tried using re module in python but it was not working. I tried below code

import re
EXPECTED_STRING = re.sub(A[0],'A',ACTUAL_STRING)

The output was same as ACTUAL_STRING

Can anyone help me on this ?

>Solution :

The { } in patterns are used as delimiters for number of occurences:

r`'a{3,6}'` # matches  'aaa' up to 'aaaaaa'

You need to escape (manualle by prepending \) or via the re.escape(pattern) method if you want to match them literally:

import re 

d = {'{{FIRST_STRING}}':"A",
     '{{SECOND_STRING}}':"B",
     '{{THIRD_STRING}}':"C"}

ACTUAL_STRING = """My first String is {{FIRST_STRING}}, 
My second String is {{SECOND_STRING}} 
and third string is {{THIRD_STRING}} """

for key, value in d.items():
    # escape the pattern
    ACTUAL_STRING = re.sub( re.escape(key), value, ACTUAL_STRING )
    print(ACTUAL_STRING)

Output:

My first String is A, 
My second String is {{SECOND_STRING}} 
and third string is {{THIRD_STRING}}  

My first String is A, 
My second String is B 
and third string is {{THIRD_STRING}} 

My first String is A, 
My second String is B 
and third string is 
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