2009-08-02 53 views
3

我使用这个REST Web服务,它返回不同的模板字符串作为URL,例如:Python字符串templater

"http://api.app.com/{foo}" 

在Ruby中,我可以再使用

url = Addressable::Template.new("http://api.app.com/{foo}").expand('foo' => 'bar') 

得到

"http://api.app.com/bar" 

有什么办法可以在Python中做到这一点?我知道%()模板,但显然他们不在这里工作。

回答

4

在Python 2.6中,如果你需要的正是这样的语法

from string import Formatter 
f = Formatter() 
f.format("http://api.app.com/{foo}", foo="bar") 

如果需要使用较早的Python版本,那么你可以解析器/正则表达式复制2.6格式类或手卷你可以这样做做到这一点。

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 = ... 

但我还没有想通了这一点。