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?
This does not do what you expect:
It is the same as:
Which is always true, since
'stringtwo'is considered a “true” value.There are two alternatives:
Or you can write separate equality tests,
Don’t use
is, becauseiscompares 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 useisunless you really want object identity.