什么是解析和替换字符串的最佳方式?
我可能有串状,什么是解析和替换字符串的最佳方式?
"""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在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这样的模板引擎。
如果您正在寻找简单的东西,请尝试查看Python's builtin Template.我使用它可以快速轻松地进行模板化,而无需安装额外的软件包。
还有新的format()方法。
最受欢迎的模板引擎问题现在已被删除:( – 2012-09-14 14:11:19
感谢Ben的提升,我删除了链接。 – chauncey 2012-09-14 19:05:42
我会推荐一个模板引擎,而不是像以前的问题中讨论的那样手动滚动您自己的代码:http://stackoverflow.com/questions/2839513/how-to-include-a-dynamic-page-contents -into-a-template – 2010-06-03 12:07:21