0 votes
1 view
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"


print "False"

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

>>> 1 ^ 1


>>> 2 ^ 1


>>> "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.2k 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 (107k 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 



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


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

Welcome to Intellipaat Community. Get your technical queries answered by top developers !