Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (1.6k points)

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):

strng1 = raw_input("string one:")

strng2 = raw_input("string two:")

if logical_xor(strng1, strng2):

    print "True"

else:

print "False"

The ^ operator seems to be bitwise, and not defined on all objects:

>>> 1 ^ 1

0

>>> 2 ^ 1

3

>>> "pqr" ^ ""

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: unsupported operand type(s) for ^: 'str' and 'str'

2 Answers

0 votes
by (33.1k points)
If you're previously normalizing the inputs to booleans, then != is xor.

bool(a) != bool(b)

Hope this answer helps you!
0 votes
by (106k points)
edited by

Python has a built-in function for bitwise exclusive-or in the operator module which is identical to the ^operator. 

See the example below:-

from operator import xor 

a=1

b=2

xor(bool(a), bool(b))

image

To know more about this you can have a look at the following video tutorial:-

Browse Categories

...