Python template

How to write a render_user function that takes one of the tuples returned by a list of users and a row pattern and returns the data substituted into the pattern, for example:

>>> tpl = "<a href='mailto:%s'>%s</a>" >>> render_user((' matt.rez@where.com ', 'matt rez', ), tpl) "<a href='mailto: matt.rez@where.com >Matt rez</a>" 

Any help would be appreciated

+7
source share
2 answers

There is no need to create a function if you do not require it:

 >>> tpl = "<a href='mailto:%s'>%s</a>" >>> s = tpl % (' matt.rez@where.com ', 'matt rez', ) >>> print s "<a href='mailto: matt.rez@where.com '>matt rez</a>" 

If you use 2.6+, you can use the new format function along with the mini-language:

 >>> tpl = "<a href='mailto:{0}'>{1}</a>" >>> s = tpl.format(' matt.rez@where.com ', 'matt rez') >>> print s "<a href='mailto: matt.rez@where.com '>matt rez</a>" 

Wrapped in function:

 def render_user(userinfo, template="<a href='mailto:{0}'>{1}</a>"): """ Renders a HTML link for a given ``userinfo`` tuple; tuple contains (email, name) """ return template.format(userinfo) # Usage: userinfo = (' matt.rez@where.com ', 'matt rez') print render_user(userinfo) # same output as above 

Additional loan:

Instead of using the regular tuple object, try using the more robust and friendly namedtuple provided by the collections module. It has the same performance (and memory consumption) as a regular tuple . A short entry into the named tuples can be found in this PyCon 2011 video (fast forward to ~ 12 m): http://blip.tv/file/4883247

+10
source
  from string import Template
 t = Template ("$ {my} + $ {your} = 10")
 print (t.substitute ({"my": 4, "your": 6}))
+4
source

All Articles