我正在使用这个REST Web服务,它返回各种模板字符串作为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实现这个功能?我知道%()模板,但显然它们在这里不起作用。
from string import Formatter
f = Formatter()
f.format("http://api.app.com/{foo}", foo="bar")
我不能给你一个完美的解决方案,但你可以尝试使用 string.Template
。
你可以预处理你的输入URL,然后直接使用 string.Template,就像这样:
In [6]: url="http://api.app.com/{foo}"
In [7]: up=string.Template(re.sub("{", "${", url))
In [8]: up.substitute({"foo":"bar"})
Out[8]: 'http://api.app.com/bar'
利用默认的"${...}"语法替换标识符,或者继承string.Template
来控制标识符模式,例如:
class MyTemplate(string.Template):
delimiter = ...
pattern = ...
但我还没有想通。