Python字符串模板生成器

3

我正在使用这个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实现这个功能?我知道%()模板,但显然它们在这里不起作用。
3个回答

4
在Python 2.6中,如果您需要确切的语法,则可以这样做。
from string import Formatter
f = Formatter()
f.format("http://api.app.com/{foo}", foo="bar")

如果您需要使用早期版本的Python,则可以复制2.6格式化程序类或手动编写解析器/正则表达式来完成。

2
不要使用快速的hack。
那里使用的是URI模板(由Addressable实现)。在Python中似乎有几个库可以实现这一点,例如:uri-templatesdescribed_routes_py也有一个解析器用于处理它们。

0

我不能给你一个完美的解决方案,但你可以尝试使用 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   = ...

但我还没有想通。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接