有没有办法用逻辑语句(不是,和,或)替换一段字符串

Is there a way to replace a piece of string with a logical statement (not, and, or)

所以,我刚刚开始学习 Python,我接到了一项任务,要编写一个程序,该程序将命题演算公式和 X、Y 和 Z(真或假)的值作为输入。然后它应该写如果答案是真还是假。公式应仅包含 3 个运算:-(非)、&(与)、v(或)。公式中的变量只能是X、Y、Z,而且都可以出现0次或多次。


可能的公式示例:

变量值应以二进制形式给出,如下所示: 010(X = f,Y = t,Z = f)。对于变量的值,我这样做了

value = input("Value: ")

X = value[0]
Y = value[1]
Z = value[2]

if X == "0":
    X = False
elif X = "1":
    X = True
else:
    print("False input")

if Y == "0":
    Y = False
elif Y = "1":
    Y = True
else:
    print("False input")

if Z == "0":
    Z = False
elif Z = "1":
    Z = True
else:
    print("False input")

很确定有更好的方法来执行此操作,但这应该仍然有效。问题在于阅读公式。我的想法是用 not、and、or 替换符号 (-,&,v)。像这样:

a = input()
print(a.replace("v", or))

但是你不能那样做,所以我不知道该怎么做。

你可以试试这个:

input_string = "--X&Y"
output_string = []
for elem in input_string:
    if elem in ["-"]:
        elem = "not "
    elif elem in ["&"]:
        elem = " and "
    elif elem in "v":
        elem = "or "
    output_string.append(elem)
print ("".join(output_string))

请注意,被替换的"or"、"and"和"not"是字符串,不是逻辑运算符。

你可以这样做:

>>> def interpret(values, formula):
...     X, Y, Z=[int(i) for i in values]
...     newF=formula.replace('-', ' not ').replace('v', ' or ').replace('&', ' and ')
...     return eval(newF)
... 
>>> val = raw_input("Value: ")
Value: 011
>>> form = raw_input("Formule : ")
Formule : -(-(YvX)&Y)
>>> interpret(val, form)
True