【问题标题】:Python convert a string to a logic operatorPython将字符串转换为逻辑运算符
【发布时间】:2014-04-04 00:34:00
【问题描述】:

例如,如果我有一个类似的表达式

x=True or True

如果我在 shell 中评估结果为真

print(x)
x=True

所以现在我想将字符串或输入转换为直接指向该逻辑表达式,例如

x=raw_input('Please give an expression:')

我知道表达式是一个字符串,那么如何将该字符串转换为逻辑表达式?

print(x)
x="True or True"

【问题讨论】:

    标签: python logical-operators boolean-expression boolean-operations string-conversion


    【解决方案1】:

    你可以使用eval()函数:

    print eval(x)
    

    注意你must be cautious在使用它的时候。

    编辑:

    正如@PriyankPatel 提到的,另一种方法是使用exec

    exec("print " + x)
    

    【讨论】:

    • exec 'print True or True'这是你想要的吗?
    • 非常感谢,正是我想要的! :D
    猜你喜欢
    • 1970-01-01
    • 2011-07-04
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 1970-01-01
    相关资源
    最近更新 更多