Python中基于字典替换字符串标签时{Prio}无法替换问题求助
问题:JIRA工单生成时部分标签替换失败
将JSON文本通过json.dumps转换为字符串后,尝试替换其中的{name}、{Prio}这类标签时,{name}替换成功,但在字符串末尾添加的{Prio}标签无法替换。期望两个标签都能被字典对应值替换,用于自动生成JIRA工单。
问题代码示例
#insert function def insert_str(string, str_to_insert, index): return string[:index] + str_to_insert + string[index:] #my demo json.dumps text = "{hello this is just a test {name}, and i want to replace}" #add a new replacement tag text = insert_str(text,", {Prio}",len(text)-1) print("String added at the end of text:") print(text) #create a key value pair dictionary key_values = {"name": "John", "age": 30, "{Prio}": "New York"} # show the dictionary print("key_values: "+str(key_values)) for key, value in key_values.items(): text = re.sub(f"{{{key}}}", str(value), text) print("") print(text)
预期结果
原字符串:
"{hello this is just a test {name}, and i want to replace, {Prio}}"
应替换为:
"{hello this is just a test John, and i want to replace, New York}"
实际只有John被正确替换,New York未替换。
问题原因
字典中{Prio}的key带了大括号,而正则替换时用了f"{{{key}}}",这会把{Prio}转成{{Prio}},也就是要匹配文本中的{{Prio}}双大括号标签,但你插入的是单大括号的{Prio},两者不匹配,所以替换失败。
解决方案
方案1:统一字典key格式(推荐)
把字典里的key都改成不带大括号的形式,和name保持一致,这样正则替换的逻辑就能统一处理:
import re #insert function def insert_str(string, str_to_insert, index): return string[:index] + str_to_insert + string[index:] text = "{hello this is just a test {name}, and i want to replace}" text = insert_str(text,", {Prio}",len(text)-1) print("String added at the end of text:") print(text) # 修改字典key,去掉大括号 key_values = {"name": "John", "age": 30, "Prio": "New York"} print("key_values: "+str(key_values)) for key, value in key_values.items(): # 正则匹配{key}格式的标签 text = re.sub(f"{{{key}}}", str(value), text) print("") print(text)
方案2:直接使用字符串replace(更简单)
如果不需要正则的复杂匹配,直接用字符串的replace方法,避免正则转义问题:
#insert function def insert_str(string, str_to_insert, index): return string[:index] + str_to_insert + string[index:] text = "{hello this is just a test {name}, and i want to replace}" text = insert_str(text,", {Prio}",len(text)-1) print("String added at the end of text:") print(text) key_values = {"{name}": "John", "age": 30, "{Prio}": "New York"} print("key_values: "+str(key_values)) for key, value in key_values.items(): # 直接替换固定字符串 text = text.replace(key, str(value)) print("") print(text)
注意:方案2中需要把name的key也改成{name},保持和文本中的标签格式一致。
内容的提问来源于stack exchange,提问作者RoDae
相关产品推荐
相关产品推荐

