Home > Article > Backend Development > How to Perform Logical XOR in Python with String Inputs?
Performing Logical XOR in Python
In Python, a common scenario involves checking whether only one of two variables holds a True value, excluding None or empty strings. Achieving this logical exclusive OR (XOR) operation requires a different approach than the bitwise XOR operator (^), which is not universally applicable.
Using != for XOR
If the input variables are already normalized to boolean values, the XOR operation can be achieved using the != (not equal to) operator. This approach effectively evaluates whether the boolean values of the two variables differ, fulfilling the XOR condition.
Example:
<code class="python">str1 = input("Enter string one:") str2 = input("Enter string two:") if bool(str1) != bool(str2): print("ok") else: print("bad")</code>
The above is the detailed content of How to Perform Logical XOR in Python with String Inputs?. For more information, please follow other related articles on the PHP Chinese website!