Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I do math inside Python's string formatting "language"?

Tags:

python

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!

like image 658
jlconlin Avatar asked Jun 21 '11 20:06

jlconlin


People also ask

Can you do math with strings in Python?

You can use the eval function to evaluate mathematical expressions in strings.

How do you write math in Python?

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.

What is the use of formatting string in Python?

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.

Can you use .format on variables Python?

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.


2 Answers

"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.

like image 129
Ben Burns Avatar answered Nov 12 '22 22:11

Ben Burns


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?

like image 39
Russell Borogove Avatar answered Nov 12 '22 23:11

Russell Borogove