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

后端 未结 3 621
别跟我提以往
别跟我提以往 2020-12-03 07:02

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...

dog = \"xdasds\"
 if \"x\" is in dog:
         


        
3条回答
  •  攒了一身酷
    2020-12-03 07:41

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

    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.

提交回复
热议问题