【问题标题】:Python string templaterPython 字符串模板
【发布时间】:2009-08-02 08:46:50
【问题描述】:

我正在使用这个 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 中做到这一点?我知道 %() 模板,但显然它们在这里不起作用。

【问题讨论】:

    标签: python ruby templates string


    【解决方案1】:

    在 python 2.6 中,如果您需要该语法,则可以这样做

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

    如果您需要使用较早的 python 版本,那么您可以复制 2.6 格式化程序类或手动滚动解析器/正则表达式来执行此操作。

    【讨论】:

      【解决方案2】:

      不要使用快速破解。

      那里使用(并由 Addressable 实现)是URI Templates。在 python 中似乎有几个库,例如:uri-templatesdescribed_routes_py 也有一个解析器。

      【讨论】:

        【解决方案3】:

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

        但我还没弄明白。

        【讨论】:

          猜你喜欢
          • 2018-05-26
          • 1970-01-01
          • 2023-04-01
          • 1970-01-01
          • 2018-07-29
          • 1970-01-01
          • 2016-09-19
          • 2011-09-08
          • 1970-01-01
          相关资源
          最近更新 更多