Skip to content
Fix Code Error

How do you get the logical xor of two variables in Python?

March 13, 2021 by Code Error
Posted By: Zach Hirsch

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

str1 = raw_input("Enter string one:")
str2 = raw_input("Enter string two:")
if logical_xor(str1, str2):
    print "ok"
else:
    print "bad"

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

>>> 1 ^ 1
0
>>> 2 ^ 1
3
>>> "abc" ^ ""
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ^: 'str' and 'str'

Solution

If you’re already normalizing the inputs to booleans, then != is xor.

bool(a) != bool(b)
Answered By: Coady

Related Articles

  • Reference — What does this symbol mean in PHP?
  • What does this symbol mean in JavaScript?
  • What's the difference between eval, exec, and compile?
  • error LNK2005: ✘✘✘ already defined in…
  • Usage of __slots__?
  • Form field border-radius is not working only on the…
  • pyspark window function from current row to a row…
  • How can I pass a wct test while rearranging children…
  • What are the undocumented features and limitations…
  • Doubts about js number representation and his bit…
  • Concatenate two char* strings in a C program
  • How do I merge two dictionaries in a single…
  • Read multiple strings and float with multiple cases in C
  • How to perform Bitwise Xor in list of list
  • Codewars Scramblies(couldn't pass the last…
  • Passing mutilple HTML fragments / other components…
  • How do you read a Python Traceback error?
  • Can't install via pip because of egg_info error
  • How can I read inputs as numbers?
  • Checking if str1 can be re-arranged as str2 wth JavaScript
  • How to catch and print the full exception traceback…
  • Passing multiple variables in @RequestBody to a…
  • Text File Parsing and convert to JSON?
  • Manually raising (throwing) an exception in Python
  • How do you easily create empty matrices javascript?
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • What does "Fatal error: Unexpectedly found nil while…
  • Programmatically generate url from path and params
  • Compare two objects in Java with possible null values
  • Bitwise operation and usage
  • memcpy() vs memmove()
  • Is it possible to make abstract classes in Python?
  • ClojureScript: How to access (not just print) the…
  • Initialize a struct from elements of a vector
  • Maximum XOR With an Element From Array | Leetcode
  • Making a Pangram function in Python but having a…
  • Python Checking a string's first and last character
  • python for increment inner loop
  • how to remove "," from a string in javascript
  • Active tab issue on page load HTML
  • Piping df into mutate + substring expression
  • String compare in Perl with "eq" vs "=="
  • Binding complex object to a component
  • What does the [Flags] Enum Attribute mean in C#?
  • Image.open() cannot identify image file - Python?
  • Cannot update nested dictionary properly
  • Python is not calling fucntions properly
  • Asking the user for input until they give a valid response
  • i have this error what is the solve for it
  • Extract and display multiple strings in a single line
  • no match for ‘operator
  • How to use parameters with HttpPost
  • memory error in python
  • comparing two strings in SQL Server
  • Split string based on a regular expression
  • C string append
  • How to concatenate strings in windows batch file for loop?
  • Keras Sequential API is replacing every layer with…
  • ValueError: invalid literal for int () with base 10
  • TypeError: 'list' object is not callable in python
  • SQL Insert Query Using C#
  • Why does C++ code for testing the Collatz conjecture…
  • What is your most productive shortcut with Vim?
  • How do I pass a string into subprocess.Popen (using…
  • Smart way to truncate long strings
  • Calculator: Back key doesnt work in Javascript
  • For-each over an array in JavaScript
  • Check if string is neither empty nor space in shell script
  • Octave using 'for' statement to show two animations…
  • What are XAND and XOR
  • Joining and comparing values of one df with first…
  • Writing a dict to txt file and reading it back?
  • JQuery string contains check
  • What is a None value?
  • DJango doesn't execute request.method == "post" with…
  • pip install mysql-python fails with…
  • What does "SyntaxError: Missing parentheses in call…
  • What is The Rule of Three?
  • How to use grpc-web in vue?
  • Case insensitive comparison of strings in shell script
  • What is a NullReferenceException, and how do I fix it?
  • Compare 2nd and 3rd field of CSV file for each row…
  • Overloading operators in typedef structs (c++)
  • Creating a "logical exclusive or" operator in Java
  • What is an optional value in Swift?
  • What is the copy-and-swap idiom?
  • Flask error when request file from server
  • Grouped bar plot in ggplot
  • Uncaught TypeError: Cannot read property 'value' of null
  • Simple way to sort strings in the (case sensitive)…
  • Importing a function from a class in another file?
  • Difference between logical addresses, and physical…
  • Count the number of occurrences of a character in a…
  • Python Traceback (most recent call last)
  • How to save traceback / sys.exc_info() values in a variable?
  • Remote end closed connection without response
  • How can I parse a CSV string with JavaScript, which…
  • How to delete an item in a list if it exists?
  • How to find memory leak in a C++ code/project?
  • Python File Error: unpack requires a buffer of 16 bytes

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Inserting multiple rows in mysql

Next Post:

How do I find the duplicates in a list and create another list with them?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error