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!
You can use the eval function to evaluate mathematical expressions in strings.
For straightforward mathematical calculations in Python, you can use the built-in mathematical operators, such as addition ( + ), subtraction ( - ), division ( / ), and multiplication ( * ). But more advanced operations, such as exponential, logarithmic, trigonometric, or power functions, are not built in.
String formatting is also known as String interpolation. It is the process of inserting a custom string or variable in predefined text. As a data scientist, you would use it for inserting a title in a graph, show a message or an error, or pass a statement to a function.
Python's str. format() method of the string class allows you to do variable substitutions and value formatting. This lets you concatenate elements together within a string through positional formatting.
"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:
N = { 'd' : 3 }
four = Template(u'number:{{ d + 1 }}').render(**N)
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.
About as close as you can get is to use positional arguments instead of keyword arguments:
four='{0:d}'.format(N['number']+1)
or the shorter old-school:
four='%d'%(N['number']+1)
What's your goal here?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With