How do you get the logical xor of two variables in Python?

Posted by Zach Hirsch on Stack Overflow See other posts from Stack Overflow or by Zach Hirsch
Published on 2009-01-11T12:34:43Z Indexed on 2010/04/20 13:23 UTC
Read the original article Hit count: 211

Filed under:
|

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"

The ^ 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'

© Stack Overflow or respective owner

Related posts about python

Related posts about logic