2016-08-15 100 views
1

是否有可能将if语句中的字符串解析为字符串?像将字符串解析为布尔值?

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

但一些被解析为

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

这可能吗?这是一个程序吗?

+0

你当然可以建立这样的事情。不过,你需要描述你想要处理的字符串的完整语法。你甚至可以评估任意的Python表达式,但这通常不是处理这种事情的安全方式。 – smarx

+0

理论上你可以写一些代码来做到这一点。为什么你需要这样做呢?你是否收到很多字符串输入? – Harrison

+0

@Harrison我正在写基于基本的语言,而不是写一个脚本来解析字符串,我想知道我是否可以传递一个字符串并以某种方式进行转换。 – baranskistad

回答

3

这就是eval的用途。

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

不过要注意eval。它会调用提供给它的任何函数。像os.system('rm -rf /'):/

+0

谢谢!这工作很好! – baranskistad

+0

(我可以在两分钟内接受答案。) – baranskistad

+5

如果使用'eval'准备承担灾难的责任。 – OregonTrail

0

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

这也可以用于非数字值。

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 >") 

输出

1.0 > 2 -> False 
2.0 > 2 -> False 
2 >= 2 -> True 
2 <= 1 -> False 
5 == 5.0 -> True 
5 <= 5.0 -> True 
5 != 5.0 -> False 
7 != 5.0 -> True 
Comparison only works for numerical values 
Can only compare with >=, ==, <=, !=, <, > 
Can only call this with 'A comparator B', like 1 > 2