Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

not equals operator(!=) not working in python string comparison

Tags:

python

string

I am trying to compare two strings in python 3.6 and if they are not equal then print a message and exit. My current code is:

location = 'United States of America'
if location.lower() != 'united states of america' or location.lower() != 'usa':
    print('Location was different = {}'.format(location.lower()))
    sys.exit()
else:
    #do something

But the above code is not able to match the two strings and even though they are equal, it enters the loop and prints that they are different. I know its some silly mistake that I am making but unable to figure it out.

like image 498
user2966197 Avatar asked Feb 22 '18 09:02

user2966197


People also ask

What is not equal to operator in Python?

In Python != is defined as not equal to operator. It returns True if operands on either side are not equal to each other, and returns False if they are equal. Note: It is important to keep in mind that this comparison operator will return True if the the values are same but are of different data types.

How to check if two strings are equal in Python?

The >= operator checks if one string is greater than or equal to another string. Since one of both conditions of the operator is true (both strings are equal), we got a value of True. In this article, we learned about the various operators you can use when checking the equality of strings in Python with examples.

What does the comparison operator do in Python?

It returns True if operands on either side are not equal to each other, and returns False if they are equal. Note: It is important to keep in mind that this comparison operator will return True if the the values are same but are of different data types. Attention geek!

How to return the opposite of a string in Python?

You can use the not equal Python operator for formatted strings (f-strings), introduced in Python 3.6. To return an opposite boolean value, use the equal operator ==. Keep in mind that some fonts change != to look like ≠ !


2 Answers

Your condition:

if location.lower() != 'united states of america' or location.lower() != 'usa':

will never be False, since location.lower() can't be 2 different strings at the same time.

I suspect you want:

if location.lower() != 'united states of america' and location.lower() != 'usa':
like image 130
llllllllll Avatar answered Oct 19 '22 18:10

llllllllll


You are looking for an AND condition instead of a OR condition in your if statement. If you change that you should be set

like image 1
Nishant Ravindran Avatar answered Oct 19 '22 19:10

Nishant Ravindran