什么是解析和替换字符串的最佳方法?

时间:2010-06-03 12:00:54

标签: python templates string-formatting replace

我可能有字符串,

"""Hello, %(name)s,
how are you today, 
here is amount needed: %(partner_id.account_id.debit_amount)d
"""

这种模板的最佳解决方案可能需要将正则表达式与eval结合起来,输入字符串可能与$partner_id.account_id.debit_amount$不同 - 目前我保持为python字符串格式 - 只是用于测试。

3 个答案:

答案 0 :(得分:2)

Python在Python 2.6和3.0中对字符串实现了一个新的.format()方法。看看这个PEP:http://www.python.org/dev/peps/pep-3101/

它比%运算符更强大,更灵活,内置于python:

以下是PEP的一些例子:

"My name is {0}".format('Fred')
"My name is {0.name}".format(open('out.txt', 'w'))
"My name is {0[name]}".format({'name':'Fred'})

如果不是这样,你的需求可能就足够了,就像其他人所说的那样,看看像Jinja这样的模板引擎。

答案 1 :(得分:1)

如果您正在寻找简单的东西,请尝试查看Python's builtin Template.我使用它可以快速轻松地模板化而无需安装额外软件包的开销。

还有新的format()方法。

答案 2 :(得分:0)

如果您要进行复杂的模板化,可以考虑使用像Jinja这样的高级模板引擎。还有很多其他的。