将字符串解析为布尔值?

2024-03-29 12:16:30 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以将if语句中的字符串解析为字符串?有点像

if "1 > 2":
    print "1 is greater than 2"

但被解析为

^{pr2}$

这可能吗?是不是有一个程序能做到这一点?在


Tags: 字符串程序ifis语句printthangreater
2条回答

如果您只是比较数值,这种方法通常会更安全。在

这也可以用于非数值。在

from operator import gt, ge, lt, le, eq, ne

def compare(expression):
    parts = expression.split()
    if len(parts) != 3:
        raise Exception("Can only call this with 'A comparator B', like 1 > 2")
    a, comp, b = parts
    try:
        a, b = float(a), float(b)
    except:
        raise Exception("Comparison only works for numerical values")
    ops = {">": gt, '<': lt, '>=': ge, '<=': le, '==': eq, '!=': ne}
    if comp not in ops:
        raise Exception("Can only compare with %s" % (", ".join(ops)))
    return ops.get(comp)(a, b)


def run_comp(expression):
    try:
        print("{} -> {}".format(expression, compare(expression)))
    except Exception as e:
        print str(e)

if __name__ == "__main__":
    run_comp("1.0 > 2")
    run_comp("2.0 > 2")
    run_comp("2 >= 2")
    run_comp("2 <= 1")
    run_comp("5 == 5.0")
    run_comp("5 <= 5.0")
    run_comp("5 != 5.0")
    run_comp("7 != 5.0")
    run_comp("pig > orange")
    run_comp("1 ! 2")
    run_comp("1 >")

输出

^{pr2}$

这就是eval的目的。在

if eval("1 > 2"):
    print "1 is greater than 2"

不过,请注意eval。它将调用提供给它的任何函数。比如os.system('rm -rf /'):/

相关问题 更多 >