How to Perform Logical XOR in Python with String Inputs?

DDD
Release: 2024-11-05 00:27:02
Original
516 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!