When using formatted string literal, it is possible to have nested f-strings to some extent.
a = 3
b = 7
res = f"{f'{a*b}'}"
print(res) # '21'
Although, the same does not work if the inner expression is a variable containing a string.
a = 3
b = 7
expr = 'a*b'
res = f"{f'{expr}'}"
print(res) # 'a*b'
Is there a way to make this work and to have the second output to be '21'
as well? If not, what is the difference between the first and second string that prevents it?
There are a few libraries that have developed functions for evaluating numerical and logical expressions safely ("safe" being the key).
First, the setup -
a = 3
b = 7
op = '*'
numexpr.evaluate
>>> import numexpr as ne
>>> ne.evaluate(f'{a} {op} {b}')
array(21, dtype=int32)
numexpr
is smart enough to optimise your expressions, and is even faster than numpy in some instances. Install using pip
.
pandas.eval
A safe eval from the Pandas API similar to ne.evaluate
.
>>> import pandas as pd
>>> pd.eval(f'{a} {op} {c}')
12
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