In Python, we can easily check if a letter is in a string using the Python in operator.

def containsLetter(string, letter):
    return letter in string

print(containsLetter("Hello World!", "H"))
print(containsLetter("Hello World!", "z"))

#Output:
True
False

When working with strings, it can be useful to know if a certain character is in a string variable.

In Python, we can easily get if a string contains a certain letter using the Python in operator.

Below is a function which will check if a letter is in a string or not for you using Python.

def containsLetter(string, letter):
    return letter in string

print(containsLetter("Hello World!", "H"))
print(containsLetter("Hello World!", "z"))

#Output:
True
False

Getting the Count of How Many Times a Letter Appears in a String in Python

The example above is useful for checking if a letter is in a string. We can also get the count of how many times a particular letter appears in a string using the Python string count() function.

Below is some sample code in Python to get the count of a letter in a string.

def countLetter(string, letter):
    return string.count(letter)

print(countLetter("Hello World!", "H"))
print(countLetter("Hello World!", "z"))

#Output:
1
0

Checking if More than 1 Letter is in a String Using Python

The above example only applies to checking 1 letter. We can generalize our solution in Python easily to be able to check for if multiple letters are in a string.

We can easily check if a string contains multiple letters using a for loop and check if each character is in our list of letters or not.

Below is a Python function which will check if a string contains certain characters.

def containsCertainChars(string, chars):
    for char in string:
        if char in chars:
           return True
    return False

print(containsCertainChars("Hello World!", "H"))
print(containsCertainChars("Hello World!", "olz"))
print(containsCertainChars("Hello World!", "z"))

#Output:
True
True
False

Hopefully this article has been useful for you to learn how to check if a letter is in a string using Python.

Categorized in:

Python,

Last Update: March 20, 2024