首页 > 解决方案 > Transform string into IF argument

问题描述

How to transform a string into a logical argument in Python, to be inserted as an argument of the if() function?

For example:

string = "(A != 0) and (B >= 5)"

How can this string be transformed into the very logic that it represents so that it can be inserted into an if() function?

标签: stringpython-3.xif-statementlogiclogical-operators

解决方案


您可以使用 eval 函数来评估字符串:

string = "(A != 0) and (B >= 5)"
if eval(string):
    doSomething()

推荐阅读