How to write a function render_user which takes one of the tuples returned by userlist and a string templat开发者_StackOverflow中文版e and returns the data substituted into the template, eg:
>>> 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
No urgent need to create a function, if you don't require one:
>>> 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're on 2.6+ you can alternatively use the new format
function along with its 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 a 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
Extra credit:
Instead of using a normal tuple
object try use the more robust and human friendly namedtuple
provided by the collections
module. It has the same performance characteristics (and memory consumption) as a regular tuple
. An short intro into named tuples can be found in this PyCon 2011 Video (fast forward to ~12m): http://blip.tv/file/4883247
from string import Template t = Template("${my} + ${your} = 10") print(t.substitute({"my": 4, "your": 6}))
精彩评论