Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is nested string literal interpolation possible?

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?

like image 384
Olivier Melançon Avatar asked Mar 07 '23 01:03

Olivier Melançon


1 Answers

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
like image 101
cs95 Avatar answered Mar 14 '23 15:03

cs95