Why can't I xor strings?
indigo at bitglue.com
Fri Oct 8 22:59:02 CEST 2004
On Fri, Oct 08, 2004 at 04:53:02PM -0400, dataangel wrote:
> Phil Frost wrote:
> >^ is the bitwise xor operator. Performing bitwise operations on strings
> >doesn't make much sense, so it's invalid. You can define a logical xor
> >function like so:
> >xor = lambda p, q: (p and not q) or (not p and q)
> >or equivalently:
> >xor = lambda p, q: bool(p) != bool(q)
> >On Fri, Oct 08, 2004 at 04:19:22PM -0400, dataangel wrote:
> >> ...
> >>Regardless of whether this is the best implementation for detecting if
> >>two strings are similar, I don't see why xor for strings shouldn't be
> >>supported. Am I missing something? Inparticular, I think it'd be cool to
> >>have "xor" as opposed to "^". The carrot would return the resulting
> >>value, while "xor" would act like and/or do and return the one that was
> >>true (if any).
> Nice =D
> But why no xor builtin? :P
I think it would be nice, but one argument is that it's not possible to
short-circut xor, both sides must be evaluated to determine the result.
Contrast this with 'and' and 'or', which know after evaluating the first
expression if it's required to evaluate the latter. For example:
0 and 123 -> 0
False and 123 -> False
123 or False -> 123
But since both sides of xor must be evaluated, there is no reason to
return one expression over the other. I would argue it should always
return True or False.
More information about the Python-list