Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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!"
like image 303
Noah R Avatar asked Feb 02 '11 17:02

Noah R


People also ask

How do you check if a string contains a specific letter in Python?

Using Python's "in" operator The simplest and fastest way to check whether a string contains a substring or not in Python is the "in" operator . This operator returns true if the string contains the characters, otherwise, it returns false .

How do you check if a string has a certain letter?

Use the String. includes() method to check if a string contains a character, e.g. if (str. includes(char)) {} . The include() method will return true if the string contains the provided character, otherwise false is returned.


3 Answers

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!" 
like image 61
ide Avatar answered Sep 28 '22 14:09

ide


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.

like image 40
pyfunc Avatar answered Sep 28 '22 14:09

pyfunc


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

like image 25
Foo Bah Avatar answered Sep 28 '22 14:09

Foo Bah