簡體   English   中英

如何替換 Python 中的精確單詞匹配

[英]How to replace an exact word match in Python

我正在嘗試使用 Python 腳本自動化我的部分工作,其中我必須替換 dbt 腳本中的一組單詞。

所以首先我有一個需要用其他值替換的子字符串的列表。

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

大括號是字符串的一部分。 現在我有以下方式的實際字符串

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

現在我想在 ACTUAL_STRING 中執行一些替換操作,以便我可以低於字符串

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

我嘗試在 python 中使用re模塊,但它不起作用。 我試過下面的代碼

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

output 與 ACTUAL_STRING 相同

誰可以幫我這個事?

模式中的{ }用作出現次數的分隔符:

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

如果您想逐字匹配它們,則需要轉義(通過預先添加\進行手動操作)或通過re.escape( pattern )方法:

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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM