snippetpythonCriticalCanonical
How do you get the logical xor of two variables in Python?
Viewed 0 times
variablesyouhowthelogicalxortwopythonget
Problem
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 an empty string):
The
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 an empty string):
str1 = raw_input("Enter string one:")
str2 = raw_input("Enter string two:")
if logical_xor(str1, str2):
print "ok"
else:
print "bad"
The
^ operator is bitwise, and not defined on all objects:>>> 1 ^ 1
0
>>> 2 ^ 1
3
>>> "abc" ^ ""
Traceback (most recent call last):
File "", line 1, in
TypeError: unsupported operand type(s) for ^: 'str' and 'str'Solution
If you're already normalizing the inputs to booleans, then != is xor.
bool(a) != bool(b)Code Snippets
bool(a) != bool(b)Context
Stack Overflow Q#432842, score: 1753
Revisions (0)
No revisions yet.