How do you get the logical xor of two variables in Python?
For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string):
str1 = raw_input("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2): print "ok" else: print "bad"
^ operator seems to be bitwise, and not defined on all objects:
>>> 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'
If you're already normalizing the inputs to booleans, then != is xor.
bool(a) != bool(b)
You can always use the definition of xor to compute it from other logical operations:
(a and not b) or (not a and b)
But this is a little too verbose for me, and isn't particularly clear at first glance. Another way to do it is:
bool(a) ^ bool(b)
The xor operator on two booleans is logical xor (unlike on ints, where it's bitwise). Which makes sense, since
bool is just a subclass of
int, but is implemented to only have the values
1. And logical xor is equivalent to bitwise xor when the domain is restricted to
logical_xor function would be implemented like:
def logical_xor(str1, str2): return bool(str1) ^ bool(str2)
Credit to Nick Coghlan on the Python-3000 mailing list.