我正在使用这个 REST 网络服务,它返回各种模板化字符串作为 url,例如:
"http://api.app.com/{foo}"
在 Ruby 中,我可以使用
url = Addressable::Template.new("http://api.app.com/{foo}").expand('foo' => 'bar')
得到
"http://api.app.com/bar"
有没有办法在 Python 中做到这一点?我知道 %() 模板,但显然它们在这里不起作用。
最佳答案
在 python 2.6 中,如果你确实需要那种语法,你可以这样做
from string import Formatter
f = Formatter()
f.format("http://api.app.com/{foo}", foo="bar")
如果您需要使用较早的 python 版本,那么您可以复制 2.6 格式化程序类或手动滚动解析器/正则表达式来执行此操作。
关于Python 字符串模板器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1218457/