问题描述
我有一些 JSON 数据:
data = '''
{
"test": "{{{test}}}"
}
'''
现在我要替换"{{{test}}}"
{{{test}}}
所以不带引号)。
硬编码它的工作原理:
new = data.replace("\"{{{test}}}\"", "{{{test}}}")
print(new)
输出:
{
"test": {{{test}}}
}
但是我需要在命令中将“test”作为变量导入,所以我尝试了:
variable = "test"
new = data.replace("\"{{{%s}}}\"", "{{{%s}}}" % variable)
print(new)
但后来我又得到了报价:
{
"test": "{{{test}}}"
}
我做错了什么,我怎样才能做到这一点?
1楼
你的问题在这里:
new = data.replace("\"{{{%s}}}\"", "{{{%s}}}" % variable)
您只对第二个值进行字符串替换。
这是一种可能更清洁的方法:
substitution = "{{{%s}}}" % variable
new = data.replace('"%s"' % substitution, substitution)
话虽如此,如果您像这样进行大量的字符串修改,您可能需要查看像这样的模板库或像这样的 compile-to-JSON 语言。 我个人更喜欢 Jsonnet,但每个人都喜欢。