Check a string for a certain Letter in Python

avatar

Borislav Hadzhiev

Last updated: Sep 19, 2022

banner

Photo from Unsplash

Check a string for a certain Letter in Python #

Use the in operator to check a string for a certain letter, e.g. if letter in string:. The in operator will return True if the letter is contained in the string, otherwise False is returned.

main.py
my_str = 'bobbyhadz.com' # ✅ check if a certain letter is contained in a string if 'z' in my_str: # 👇️ this runs print('The letter is contained in the string') else: print('The letter is NOT contained in the string') # ---------------------------------------------- # ✅ check if a certain letter is NOT contained in a string if 'z' not in my_str: print('The letter is NOT contained in the string') else: # 👇️ this runs print('The letter is contained in the string')

We used the in operator to check if a string contains a certain letter.

The in operator tests for membership. For example, x in s evaluates to True if x is a member of s, otherwise it evaluates to False.

main.py
my_str = 'bobby hadz' print('bobby' in my_str) # 👉️ True print('another' in my_str) # 👉️ False

If you need to check if a certain letter is contained in a string ignoring the case, convert both strings to lowercase.

main.py
my_str = 'BOBBY HADZ' letter = 'z' if letter.lower() in my_str.lower(): # 👇️ this runs print('The letter is contained in the string') else: print('The letter is NOT contained in the string')

The str.lower method returns a copy of the string with all the cased characters converted to lowercase.

The method doesn't change the original string, it returns a new string. Strings are immutable in Python.

Converting both strings to lowercase or uppercase allows for a case-insensitive membership test.

If you need to check if a certain letter is not contained in a string, use the not in operator.

main.py
my_str = 'bobbyhadz.com' print('x' not in my_str) # 👉️ True if 'x' not in my_str: # 👇️ this runs print('The letter is NOT contained in the string') else: print('The letter is contained in the string')
x not in s returns the negation of x in s.

If you need to check if the letter is not contained in the string in a case-insensitive manner, convert both strings to lowercase.

main.py
my_str = 'bobbyhadz.com' letter = 'X' print(letter.lower() not in my_str.lower()) # 👉️ True
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.