Python 使用string.Template将键替换为具有给定参数的映射字典
我的标题听起来可能没什么帮助,但举个例子应该能说明这一点 给定此示例词典:Python 使用string.Template将键替换为具有给定参数的映射字典,python,dictionary,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中的所有内容,然后替换以下键 除了使用strin
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
键之外,是否有一种简单而优雅的方法来执行此操作?如果您确实需要使用模板而不是string.format()
或使用who
键,您可以使用两个模板
Template(Template("Hello $who").safe_substitute(d)).safe_substitute(name = "John Doe")
我也想过这个解决方案,但不认为它是一个优雅的解决方案。我真的不需要使用格式
,但是如果所有的替换都可以通过一个函数调用来完成,那就太好了。唯一的要求是可以通过字典进行格式化。模板(“Hello”+d[“who”])。安全替换(name=“John Doe”)
那么?我不认为有无限多的方法,但我可能是错的。。。