Evaluating a mathematical expression in a string

前端 未结 11 1224
名媛妹妹
名媛妹妹 2020-11-21 05:01
stringExp = \"2^4\"
intVal = int(stringExp)      # Expected value: 16

This returns the following error:

Traceback (most recent call         


        
11条回答
  •  花落未央
    2020-11-21 05:20

    [I know this is an old question, but it is worth pointing out new useful solutions as they pop up]

    Since python3.6, this capability is now built into the language, coined "f-strings".

    See: PEP 498 -- Literal String Interpolation

    For example (note the f prefix):

    f'{2**4}'
    => '16'
    

提交回复
热议问题