# Why can't I xor strings?

Alex Martelli aleaxit at yahoo.com
Mon Oct 11 09:24:44 CEST 2004

```Grant Edwards <grante at visi.com> wrote:
...
> used to thinking of ^ as a bitwise operator.  What if you saw
>
>   string1 xor string2?
>
> Wouldn't you expect it to be equivalent to
>
>   (string1 and (not string2)) or ((not string1) and string2)

Personally, I would not expect 'xor' to be non-commutative, and yet the
expression YOU apparently would expect it to be equivalent to obviousy
is...:

'foo' xor ''

would be True, while

'' xor 'foo'

would be 'foo'.  At least, that's how the "equivalent to" expression you
give evaluates, I believe.  The problem is that "not x" is a bool for
any x, while "x and y" isn't.

If I had to design the least-astonishing definition of xor in Python, I
would probably have to settle for a mix of the type-producing behavior
of and/or (always return one of the two operands, a wonderful thing) vs
not (always return a bool, and it's hard to imagine it doing otherwise).
"a xor b" would return one of the two operands if exactly one of them
evaluates to true in a boolean context, but False if both or neither do
(sigh).
E.g.,

def xor(a, b):
if (a and b) or (not a and not b): return False
else: return a or b

Unfortunately, it seems to me that his unholy admixture of return types
(hard to avoid...), as well as the inevitable lack of short-circuiting,
makes such a hypothetical 'xor' _WAY_ less useful than the existing
'and'/'or' operators are:-(

Alex

```