在Python中,如何获得两个变量的逻辑异或?
例如,我有两个变量,我希望它们都是字符串。我想测试只有其中一个包含True值(不是None或空字符串):
str1 = raw_input("Enter string one:")
str2 = raw_input("Enter string two:")
if logical_xor(str1, str2):
print "ok"
else:
print "bad"
^ 运算符是按位运算符,不适用于所有对象:
>>> 1 ^ 1
0
>>> 2 ^ 1
3
>>> "abc" ^ ""
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ^: 'str' and 'str'
a xor a
被定义为(a and not b) or (not a and b)
,因此当a
和b
为字符串或任何其他类型时,a xor b
应该产生(a and not b) or (not a and b)
的结果。 - Kazint("0xFFFF00", 16) ^ int("0xFFFF00", 16) == int(0)
,所以你必须将其转换为数字并在结果上调用hex
,然后在左侧填充足够多的 0 以达到最长长度。 - Guimoute