[Tutor] string.Template
Chris “Kwpolska” Warrick
kwpolska at gmail.com
Tue Apr 23 16:47:05 CEST 2013
On Tue, Apr 23, 2013 at 4:14 PM, Albert-Jan Roskam <fomcl at yahoo.com> wrote:
> Hello,
>
> Is there a better, *built-in* alternative for the code below? The recursion works,
> but it feels like reinventing the wheel.
>
> 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())
>
> Thank you!
>
> Regards,
> Albert-Jan
>
>
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a
> fresh water system, and public health, what have the Romans ever done for us?
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
1. locals() is hacky and you shouldn’t use it.
2. Do you need “$”? Why not use the newfangled {} syntax (since
Python 2.6)? Example:
'2 + 2 = {val}'.format(val='fish')
Or:
'2 + 2 = {0}'.format('fish')
Or even:
'2 + 2 = {}'.format('fish')
3. I doubt that there is anything better if you want $.
--
Kwpolska <http://kwpolska.tk> | GPG KEY: 5EAAEA16
stop html mail | always bottom-post
http://asciiribbon.org | http://caliburn.nl/topposting.html
More information about the Tutor
mailing list