Python 如何检查变量是否等于一个字符串或另一个字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12774279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a variable is equal to one string or another string?
提问by Rahul Sharma
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?
这不起作用!我有一个变量,当它是其中一个值时,我需要它做一些事情,但它不会进入 if 语句。在 Java 中if (var == "stringone" || "stringtwo")工作。我如何用 Python 写这个?
采纳答案by Dietrich Epp
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.
这总是正确的,因为'stringtwo'被认为是“真实”值。
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 iscompares 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 isunless you really want object identity.
不要使用is,因为is比较对象标识。有时你可能会因为 Python 实习了很多字符串而侥幸逃脱,就像你在 Java 中可以逃脱因为 Java 实习了很多字符串一样。但是is除非您真的想要对象标识,否则不要使用。
>>> 'a' + 'b' == 'ab'
True
>>> 'a' + 'b' is 'abc'[:2]
False # but could be True
>>> 'a' + 'b' is 'ab'
True # but could be False
回答by Lingfeng Xiong
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.
'is' 用于检查两个引用是否指向同一个对象。它比较内存地址。显然,'stringone' 和 'var' 是不同的对象,它们只包含相同的字符串,但它们是类 'str' 的两个不同实例。所以它们当然有两个不同的内存地址,'is' 将返回 False。
回答by inspectorG4dget
if var == 'stringone' or var == 'stringtwo':
do_something()
or more pythonic,
或者更多的pythonic,
if var in ['string one', 'string two']:
do_something()
回答by Andrew Jaffe
Two separate checks. Also, use ==rather than isto check for equality rather than identity.
两个单独的检查。此外,使用==而不是is检查相等性而不是身份。
if var=='stringone' or var=='stringtwo':
dosomething()
回答by Yaseer Arafat
for a in soup("p",{'id':'pagination'})[0]("a",{'href': True}):
if createunicode(a.text) in ['<','<']:
links.append(a.attrMap['href'])
else:
continue
It works for me.
这个对我有用。

