Search code examples
pythonpython-3.xexpression-evaluationf-string

Evaluating variable contain mathematical expression in f-strings


I have to accept input (using raw_input()) as a power expression like 10**5 and then print its value. I have tried a few pieces of code but these do not give desired results:

print(f'{2**4}') #<-- prints 16 correctly
a = '{2**4}'
print(f'{{}}'.format(a)) #<-- prints {2**4}

Is it possible to achieve something like:

var = '2**4'
print(f'{<some way to expand var in here>}') #<-- prints 16

Solution

  • In f-strings expressions are parsed with the equivalent of:

    ast.parse('(' + expression + ')', '<fstring>', 'eval')
    

    see https://docs.python.org/3/library/ast.html#ast.parse

    But variables will be replaced with their actual value. What are you looking for is sort of a nested evaluation which is not supported by f-strings. Instead as a safe approach you can first split with '**' then covert to int and finally use power:

    In [9]: s = "2**4"
    
    In [10]: print(f"{pow(*map(int, s.split('**')))}")
    16