views:

65

answers:

3

I may have string like,

"""Hello, %(name)s,
how are you today, 
here is amount needed: %(partner_id.account_id.debit_amount)d
"""

what would be the best solution for such template may i need to combine regular expression and eval, input string may differ like $partner_id.account_id.debit_amount$ - for the moment I've kept as python string format - just for testing.

A: 

If you are going to do sophisticated templating, you may consider using an advanced template engine like Jinja. There are plenty others as well.

Olivier
+2  A: 

Python implemented a new .format() method on strings in Python 2.6 and 3.0. Check out this PEP: http://www.python.org/dev/peps/pep-3101/

It is more powerful and flexible than the % operator and built into python:

Here are some examples from the PEP:

"My name is {0}".format('Fred')
"My name is {0.name}".format(open('out.txt', 'w'))
"My name is {0[name]}".format({'name':'Fred'})

It may be enough for your needs, if not, look at a templating engine like Jinja as others mentioned.

+1  A: 

If you're looking for something simple, try looking at Python's builtin Template. I use it quite a bit for quick and easy templating without the overhead of installing additional packages.

There's also the new format() method.

If you're doing something more substantial, you can try one of the many good templating engines. SO-favorite templating engine

chauncey