I would like to do some simple math while I’m doing string formatting. For example
N = {'number':3}
four = '{number:d + 1}'.format(**N)
This doesn’t work (of course). Is there a way to accomplish this that I’m not aware of?
Thanks!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
“Is there a way to accomplish this that I’m not aware of?” If by “this” you mean encoding some mathematical logic in the format string using str.format, then no — not that I’m aware of. However if you use a templating language you can express all kinds of stuff like this.
There are a billion different options for templating languages in Python, so rather than try to say which is best, I’ll let you decide. See this article from the Python wiki: http://wiki.python.org/moin/Templating
A favorite of mine is Jinja2, although it’s probably overkill for what you’re talking about.
Here’s an example of how to accomplish what you’re after with Jinja2:
The main advantage to a templating system like Jinja2 is that it allows you store templates as files separate from your application control logic such that you can maintain the view/presentation logic for your program in a way that limits or prohibits side effects from presentation execution.