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!
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!
"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?
It is year 2023, we can consider this solution here: https://stackoverflow.com/a/53671539/4563935
For your example, this works:
def fstr(template):
return eval(f"f'{template}'")
number = 3
number_plus_one = "{number + 1}"
print(fstr(number_plus_one))