简体   繁体   中英

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

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?

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM