Python中的模板

9 投票
2 回答
4116 浏览
提问于 2025-04-16 14:09

如何编写一个名为 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>"

任何帮助都非常感谢

2 个回答

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

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。

12

如果你不需要的话,其实没必要创建一个函数:

>>> 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>"

如果你使用的是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>"

把它放在一个函数里:

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

额外提示:

与其使用普通的tuple对象,不如试试collections模块里提供的更强大、更易于理解的namedtuple。它的性能和内存使用跟普通的tuple是一样的。关于命名元组的简短介绍,可以在这个PyCon 2011的视频中找到(快进到大约12分钟):http://blip.tv/file/4883247

撰写回答