[Tutor] string.Template
Steven D'Aprano
steve at pearwood.info
Tue Apr 23 16:55:06 CEST 2013
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? The following looks like a perfectly sensible use for recursion. If your replacement strings themselves contain $-template strings, and you want to replace them as well, recursion seems like a good call.
Although, of course, the recursion may not converge on a single result. Consider what happens if you use the following replacement strings:
$spam -> $eggs
$eggs -> $spam
> import string
>
> def translate(template, *args):
> """Recursively $-substitute <template> using <args> as a replacement"""
> syntax = string.Template(template).substitute(*args)
> if "$" in syntax:
> return translate(syntax, *args)
> return syntax
>
> template = """\
> Monty $surname
> $more
> """
> more = """\
> The quest for the holy $grail
> """
> surname="Python"
> grail="Grail"
> print translate(template, locals())
--
Steven
More information about the Tutor
mailing list