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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4877844/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 17:56:39  来源:igfitidea点击:

How would I check a string for a certain letter in Python?

python

提问by Noah R

How would I tell Python to check the below for the letter x and then print "Yes"? The below is what I have so far...

我如何告诉 Python 检查下面的字母 x 然后打印“是”?以下是我到目前为止...

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

采纳答案by ide

Use the inkeyword without is.

使用in不带的关键字is

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

If you'd like to check for the non-existence of a character, use not in:

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

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

回答by pyfunc

inkeyword allows you to loop over a collection and check if there is a member in the collection that is equal to the element.

in关键字允许您遍历集合并检查集合中是否有与元素相等的成员。

In this case string is nothing but a list of characters:

在这种情况下,字符串只不过是一个字符列表:

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

You can check a substring too:

您也可以检查子字符串:

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

Think collection:

认为收藏:

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

You can also test the set membership over user defined classes.

您还可以在用户定义的类上测试集合成员资格。

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

对于定义 __contains__ 方法的用户定义类,当且仅当 y.__contains__(x) 为真时,y 中的 x 为真。

回答by Foo Bah

If you want a version that raises an error:

如果您想要一个引发错误的版本:

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

If you want a version that returns -1:

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

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

This is more efficient than the 'in' syntax

这比“in”语法更有效