2024-10-06 10:27:12 发布
网友
我如何让Python检查下面的字母x,然后打印“Yes”?下面是我到目前为止所拥有的。。。
dog = "xdasds" if "x" is in dog: print "Yes!"
in关键字允许您在集合上循环并检查集合中是否有等于元素的成员。
in
在本例中,字符串只是一个字符列表:
dog = "xdasds" if "x" in dog: print "Yes!"
也可以检查子字符串:
>>> 'x' in "xdasds" True >>> 'xd' in "xdasds" True >>> >>> >>> 'xa' in "xdasds" False
Think系列:
>>> '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.
如果需要引发错误的版本:
"string to search".index("needle")
如果要返回-1的版本:
"string to search".find("needle")
这比“in”语法更有效
使用不带is的in关键字。
is
if "x" in dog: print "Yes!"
如果要检查字符是否不存在,请使用not in:
not in
if "x" not in dog: print "No!"
in
关键字允许您在集合上循环并检查集合中是否有等于元素的成员。在本例中,字符串只是一个字符列表:
也可以检查子字符串:
Think系列:
您还可以在用户定义的类上测试集合成员资格。
如果需要引发错误的版本:
如果要返回-1的版本:
这比“in”语法更有效
使用不带
is
的in
关键字。如果要检查字符是否不存在,请使用
not in
:相关问题 更多 >
编程相关推荐