在Python中,如何检查某个字母的字符串?

2024-10-06 10:27:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我如何让Python检查下面的字母x,然后打印“Yes”?下面是我到目前为止所拥有的。。。

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

Tags: inifis字母yesprintdogxdasds
3条回答

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”语法更有效

使用不带isin关键字。

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

如果要检查字符是否不存在,请使用not in

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

相关问题 更多 >