python - python中的模板

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

任何帮助将不胜感激

最佳答案

如果您不需要一个功能,则无需紧急创建:

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

额外学分:

尝试使用更健壮和人性化的 namedtuple 而不是使用普通的 tuple 对象由 collections 模块提供。它具有与常规 tuple 相同的性能特征(和内存消耗)。可以在这个 PyCon 2011 视频(快进到 ~12m)中找到对命名元组的简短介绍:http://blip.tv/file/4883247

关于python - python中的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5385397/

相关文章:

java - 在字符串中查找特定标记的最佳方法(在 Java 中)是什么?

c++ - 在可变参数模板函数中同时接受 int 和 class?

c++ - 类模板的模板参数推导陷阱

php - 有条件地在 magento 布局中添加 block

python - 如何在终止子进程后自动从 Popen 获取返回码?

Python:在单独的脚本中动态调用方法

php - 如何获取正则表达式匹配在字符串中的位置?

java - 为什么要使用new创建String对象

python - 如何将键映射到多个值到数据框列?

python - 文件 "pylab.py"的用途是什么