Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string templater

I'm using this REST web service, which returns various templated strings as urls, for example:

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

In Ruby, I can then use

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

to get

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

Is there any way to do this in Python? I know about %() templates, but obviously they're not working here.

like image 278
Dmitry Shevchenko Avatar asked Feb 26 '26 03:02

Dmitry Shevchenko


2 Answers

In python 2.6 you can do this if you need exactly that syntax

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

If you need to use an earlier python version then you can either copy the 2.6 formatter class or hand roll a parser/regex to do it.

like image 52
Peter Ellis Avatar answered Feb 28 '26 17:02

Peter Ellis


Don't use a quick hack.

What is used there (and implemented by Addressable) are URI Templates. There seem to be several libs for this in python, for example: uri-templates. described_routes_py also has a parser for them.

like image 45
Skade Avatar answered Feb 28 '26 18:02

Skade



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!