Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a variable is equal to one string or another string? [duplicate]

Tags:

python

if var is 'stringone' or 'stringtwo':
    dosomething()

This does not work! I have a variable and I need it to do something when it is either of the values, but it will not enter the if statement. In Java if (var == "stringone" || "stringtwo") works. How do I write this in Python?

like image 850
Rahul Sharma Avatar asked Oct 08 '12 01:10

Rahul Sharma


3 Answers

This does not do what you expect:

if var is 'stringone' or 'stringtwo':
    dosomething()

It is the same as:

if (var is 'stringone') or 'stringtwo':
    dosomething()

Which is always true, since 'stringtwo' is considered a "true" value.

There are two alternatives:

if var in ('stringone', 'stringtwo'):
    dosomething()

Or you can write separate equality tests,

if var == 'stringone' or var == 'stringtwo':
    dosomething()

Don't use is, because is compares object identity. You might get away with it sometimes because Python interns a lot of strings, just like you might get away with it in Java because Java interns a lot of strings. But don't use is unless you really want object identity.

>>> 'a' + 'b' == 'ab'
True
>>> 'a' + 'b' is 'abc'[:2]
False # but could be True
>>> 'a' + 'b' is 'ab'
True  # but could be False
like image 137
Dietrich Epp Avatar answered Nov 01 '22 16:11

Dietrich Epp


if var == 'stringone' or var == 'stringtwo':
    do_something()

or more pythonic,

if var in ['string one', 'string two']:
    do_something()
like image 32
inspectorG4dget Avatar answered Nov 01 '22 18:11

inspectorG4dget


if var == 'stringone' or var == 'stringtwo':
    dosomething()

'is' is used to check if the two references are referred to a same object. It compare the memory address. Apparently, 'stringone' and 'var' are different objects, they just contains the same string, but they are two different instances of the class 'str'. So they of course has two different memory addresses, and the 'is' will return False.

like image 7
Lingfeng Xiong Avatar answered Nov 01 '22 17:11

Lingfeng Xiong