解析字符串并用其值替换字符串的最佳方法是什么?
我可能有这样的字符串,
"""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 字符串格式 - 只是为了测试。
I may have string like,
"""Hello, %(name)s,
how are you today,
here is amount needed: %(partner_id.account_id.debit_amount)d
"""
what would be the best solution for such template may i need to combine regular expression and eval
, input string may differ like $partner_id.account_id.debit_amount$
- for the moment I've kept as python string format - just for testing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Python 在 Python 2.6 和 3.0 中对字符串实现了新的 .format() 方法。查看此 PEP:http://www.python.org/dev/peps/ pep-3101/
它比 % 运算符更强大、更灵活,并且内置于 python 中:
以下是 PEP 中的一些示例:
它可能足以满足您的需求,如果不能,请查看像 Jinja 这样的模板引擎其他人提到。
Python implemented a new .format() method on strings in Python 2.6 and 3.0. Check out this PEP: http://www.python.org/dev/peps/pep-3101/
It is more powerful and flexible than the % operator and built into python:
Here are some examples from the PEP:
It may be enough for your needs, if not, look at a templating engine like Jinja as others mentioned.
如果您正在寻找简单的东西,请尝试查看 Python 的内置模板 我经常使用它来快速、轻松地构建模板,而无需安装额外的软件包。
还有新的 format() 方法。
If you're looking for something simple, try looking at Python's builtin Template. I use it quite a bit for quick and easy templating without the overhead of installing additional packages.
There's also the new format() method.
如果您要做复杂的模板,您可以考虑使用高级模板引擎,例如 Jinja。还有很多其他的。
If you are going to do sophisticated templating, you may consider using an advanced template engine like Jinja. There are plenty others as well.