Why can't I xor strings?

Andrew Dalke adalke at mindspring.com
Sun Oct 10 11:52:00 CEST 2004


Paul Rubin wrote:
> I think != is appropriate in this situation.  
>    if bool(x) != bool(y): ...

while I prefer my already mentioned

   if bool(x) + bool(y) == 1:
     print "One and only one given"

That's because the pure logic ones, both != and
xor, confuse me while arithmetic doesn't.

It's also extensible to, say, "all three
parameters are either empty strings or non-empty
strings".

   if 0 < bool(x) + bool(y) + bool(z) < 3:
     print "that's not allowed"

BTW, I've used an idiom like this with some
success

   def blah(filename = None, infile = None, url = None):
     if (bool(filename is None) + bool(infile is None) +
         bool(url is None)) != 2:
       raise TypeError("Must specify one and only one of "
                       "'filename', 'infile', or 'url'")
     if filename is not None:
       infile = open(filename)
     elif url is not None:
       infile = urllib.urlopen(url)
     ...


Try that with an xor.

				Andrew
				dalke at dalkescientific.com



More information about the Python-list mailing list