使用string.Template替换带有给定参数

时间:2016-04-18 14:45:12

标签: python dictionary

我的标题听起来可能非常无益,但一个例子应该澄清。

鉴于此示例字典:

d = { "who" : "world! My Name is $name" }

我想使用string.Template类来代替:

Template("Hello $who").safe_substitute(d, name = "John Doe")

$name键永远不会被给定值替换。我猜因为钥匙在dict里面。我期待string.Template首先替换d内的所有内容,然后替换以下密钥。

除了使用string.format()并将{}放在键who之外,是否有一种简单而优雅的方法可以执行此操作?

1 个答案:

答案 0 :(得分:0)

如果您确实需要使用Template代替string.format()或使用密钥who,则可以使用两个模板。

Template(Template("Hello $who").safe_substitute(d)).safe_substitute(name = "John Doe")