Python 字符串模板器

标签 python ruby templates string

我正在使用这个 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/

相关文章:

python - Socket.io python 服务器

python - 使用terminaltables,如何将所有数据保存在单个表中,而不是拆分到多个表中?

python - Python 3 中的相对导入问题

Ruby Sinatra - 为公共(public)文件夹中的文件添加自定义路由

c++ - 此代码示例中使用了哪种模板特化?

python - 在 python 中调用 java 时,输出进入 stderr

ruby - 如何使用 Puma 或 Unicorn 启动一个最小的 ruby​​ 应用程序?

ruby - HAML 和迭代 XML

python - Django:为每个实例注册模板过滤器/标签

Azure 模板 - 根据所选资源组动态生成参数值