[Tutor] string.Template

Albert-Jan Roskam fomcl at yahoo.com
Tue Apr 23 21:35:51 CEST 2013



> Subject: Re: [Tutor] string.Template
> 
> 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

template = """\
Monty %(surname)s
%(more)s
"""
more = """\
The quest for the holy %(grail)s
"""
surname="Python"
grail="Grail"
print translate(template, locals())



More information about the Tutor mailing list