2011-02-02 59 views

回答

33

使用in关键字没有is

if "x" in dog: 
    print "Yes!" 

如果你想检查一个字符的不存在,使用not in

if "x" not in dog: 
    print "No!" 
6

in关键字可以遍历集合,并检查是否有一个成员等于元素的集合。

在这种情况下字符串是什么,但字符的列表:

dog = "xdasds" 
if "x" in dog: 
    print "Yes!" 

您可以检查一个子太:

>>> 'x' in "xdasds" 
True 
>>> 'xd' in "xdasds" 
True 
>>> 
>>> 
>>> 'xa' in "xdasds" 
False 

想想集合:

>>> 'x' in ['x', 'd', 'a', 's', 'd', 's'] 
True 
>>> 

你也可以在用户定义的类上测试设置的成员资格。

For user-defined classes which define the __contains__ method, x in y is true if and only if y.__contains__(x) is true.

1

如果您希望引发错误的一个版本:

"string to search".index("needle") 

如果你想返回-1的版本:

"string to search".find("needle") 

这是比 '中' 更有效语法

+0

什么?你是如何发现它更高效的?你有时间吗?或者是某种智慧?在我的设置你的代码是慢得多,更不用说不pythonic – SilentGhost 2011-02-02 18:11:50

相关问题