Tar*_*ara 7 python string format templates
如何编写一个函数render_user,它接受userlist返回的一个元组和一个字符串模板,并返回替换到模板中的数据,例如:
>>> 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>"
Run Code Online (Sandbox Code Playgroud)
任何帮助,将不胜感激
mik*_*iku 10
如果您不需要,不需要创建函数:
>>> 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>"
Run Code Online (Sandbox Code Playgroud)
如果您使用2.6+,您可以使用新format功能及其迷你语言:
>>> 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>"
Run Code Online (Sandbox Code Playgroud)
包含在一个功能中:
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
Run Code Online (Sandbox Code Playgroud)
额外信用:
而不是使用普通tuple对象尝试使用模块namedtuple提供的更强大和人性化collections.它具有与常规相同的性能特征(和内存消耗)tuple.在这个PyCon 2011视频中可以找到命名元组的简短介绍(快进到~12m):http://blip.tv/file/4883247