python中的模板

python中的模板,python,string,templates,format,Python,String,Templates,Format,如何编写函数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>

如何编写函数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>"
>>tpl=“”
>>>渲染用户(('matt)。rez@where.com“,”马特·雷兹“,第三方物流)
""

如果您不需要函数,则无需立即创建函数,任何帮助都将不胜感激:

>>> 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>"
包装在函数中:

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
def render_user(userinfo,template=”“):
“”“为给定的``userinfo``元组呈现HTML链接;
元组包含(电子邮件,名称)“”
返回模板.format(userinfo)
#用法:
userinfo=('matt。rez@where.com“,”马特·雷兹“)
打印渲染用户(用户信息)
#输出同上
额外学分:

不要使用普通的
元组
对象,尝试使用
集合
模块提供的更健壮、更人性化的对象。它与常规的
元组
具有相同的性能特征(和内存消耗)。在这个PyCon 2011视频中可以找到命名元组的简短介绍(快进到~12m):

从字符串导入模板 t=模板(“${my}+${your}=10”) 打印(t.替换({“我的”:4,“你的”:6}))
非常感谢,但是我必须用函数来编写它,它与上面的代码类似还是我应该添加更多的代码?@miku你能添加关于使用命名元组的详细信息吗?blip.tv文件已被删除,PyCon 2011在youtube上列出了许多结果。。。我已经检查了几个相关的SO答案,还没有找到一个明确的例子(obv不理解文档)-TIA!
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
from string import Template t = Template("${my} + ${your} = 10") print(t.substitute({"my": 4, "your": 6}))