Check If String Contains Any Letters from Alphabet in Python (Example)

 

On this page, I’ll explain how to test whether a character string contains one or multiple alphabetical letters using the Python programming language.

 

Example Data

As a first step, we have to create some example strings in Python:

my_string1 = "25482x736y54"                  # Create character string with letters
my_string2 = "395634875"                     # Create character string without letters

As you can see, we have created two different character strings called my_string1 and my_string2.

You may already have noticed that the first string contains letters of the alphabet, but the second string does only consist of numbers.

However, let’s check this using some Python code!

 

Example: Test for Alphabetical Letters Using the any() & isalpha() Functions

This example demonstrates how to use the any and isalpha functions to check if a character string contains a letter from the alphabet.

Let’s check our first character string my_string1:

print(any(c.isalpha() for c in my_string1))  # Check if letters are contained in string
# True

As you can see, the logical value True has been returned, i.e. our first example string contains alphabetical letters.

Let’s apply exactly the same Python syntax to our second string:

print(any(c.isalpha() for c in my_string2))  # Check if letters are contained in string
# False

This time, the logical value False has been returned, i.e. our second string does not contain any letters.

 

Video, Further Resources & Summary

Do you need more explanations on how to identify alphabetical characters in a string? Then you might have a look at the following YouTube video of the Master Code Online channel. In this video, the speaker explains how to apply the isalpha function in Python.

 

Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.

YouTube Content Consent Button Thumbnail

YouTube privacy policy

If you accept this notice, your choice will be saved and the page will refresh.

 

Furthermore, you may have a look at the other Python tutorials on Statistics Globe. Check out the link below!

 

Summary: In this tutorial, I have shown how to find letters in a character string using Python. However, in case you have further questions on this topic, you may leave me a comment below!

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top