[英]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.