[Tutor] string.Template
Prasad, Ramit
ramit.prasad at jpmorgan.com
Tue Apr 23 22:59:31 CEST 2013
Albert-Jan Roskam wrote:
> > On 24/04/13 00:14, Albert-Jan Roskam wrote:
> >> Hello,
> >>
> >> Is there a better, *built-in* alternative for the code below? The recursion
> > works,
> >> but it feels like reinventing the wheel.
> >
> > What makes you think it is reinventing the wheel?
>
> Hi Steven,
>
> Well, using a template they way I am doing seems a very common thing to do to me. So I thought it
> would be part of string.Template or something similar already. Maybe I expected more of
> string.Template after having read a little about Django's template system for the past days. ;-) This
> version does not require the string module, and it's not less readable IMHO:
>
> def translate(template, args):
> """Recursively %-substitute <template> using <args> as a replacement"""
> syntax = template % args
> if "%" in syntax:
> return translate(syntax, args)
> return syntax
Just a side note, if you ever need to have a string with "%" in it, this will
recurse infinitely (or rather until Python throws an exception).
t = "Monty Python is #@!#%% %(status)s"
translate(t, {'status': 'awesome!'})
~Ramit
This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.
More information about the Tutor
mailing list