9

How to write a function render_user which takes one of the tuples returned by userlist and a string template and returns the data substituted into the template, eg:

>>> tpl = "<a href='mailto:%s'>%s</a>"
>>> render_user(('[email protected]', 'matt rez', ), tpl)
"<a href='mailto:[email protected]>Matt rez</a>"

Any help would be appreciated

2 Answers 2

12

No urgent need to create a function, if you don't require one:

>>> tpl = "<a href='mailto:%s'>%s</a>"
>>> s = tpl % ('[email protected]', 'matt rez', )

>>> print s
"<a href='mailto:[email protected]'>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('[email protected]', 'matt rez')

>>> print s
"<a href='mailto:[email protected]'>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 = ('[email protected]', '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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot,but I have to write it with function ,Is it similar to above codes or I should add more codes?
@miku Could you add detail about using a named tuple? The blip.tv file has been removed, and PyCon 2011 lists many results on youtube... I've checked a couple of related SO answers, and haven't found a clear example yet (obv didn't understand the documentation) - TIA!
4
from string import Template
t = Template("${my} + ${your} = 10")
print(t.substitute({"my": 4, "your": 6}))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.