Evaluating a mathematical expression in a string

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

This returns the following error:

Traceback (most recent call         


        
11条回答
  •  梦毁少年i
    2020-11-21 05:27

    I think I would use eval(), but would first check to make sure the string is a valid mathematical expression, as opposed to something malicious. You could use a regex for the validation.

    eval() also takes additional arguments which you can use to restrict the namespace it operates in for greater security.

提交回复
热议问题