我想创建在数组中查找字符串的函数,然后替换字典中的对应元素。到目前为止,我已经尝试过了,但我无法弄清楚像
- 如何转义特殊字符
- 我可以用找到的匹配替换。我试过
\1
但没用
dsds
def myfunc(h):
myarray = {
"#":"\\#",
"$":"\\$",
"%":"\\%",
"&":"\\&",
"~":"\\~{}",
"_":"\\_",
"^":"\\^{}",
"\\":"\\textbackslash{}",
"{":"\\{",
"}":"\\}"
}
pattern = "[#\$\%\&\~\_\^\\\\\{\}]"
pattern_obj = re.compile(pattern, re.MULTILINE)
new = re.sub(pattern_obj,myarray[\1],h)
return new