33

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:
      print "Yes!"
Noah R
  • 5,287
  • 21
  • 56
  • 75

3 Answers3

58

Use the in keyword without is.

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

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

if "x" not in dog:
    print "No!"
ide
  • 19,942
  • 5
  • 64
  • 106
7

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.

pyfunc
  • 65,343
  • 15
  • 148
  • 136
3

If you want a version that raises an error:

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

If you want a version that returns -1:

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

This is more efficient than the 'in' syntax

Foo Bah
  • 25,660
  • 5
  • 55
  • 79
  • What? how did you find out that it's more efficient? Did you time it? or is it some sort of wisdom? On my setup your code is much slower, not to mention not pythonic – SilentGhost Feb 02 '11 at 18:11