check if string contains only letters in python

Python – Check If String Contains Only Letters

In this tutorial, we will look at how to check whether a string contains only letters or not in Python with the help of examples.

check if string contains only letters in python

You can use the string isalpha() function to check if a string contains only letters (that is, alphabets) in Python. The following is the syntax –

# check if string s contains only letters
s.isalpha()

It returns True if all the characters in the string are alphabets. If any of the characters is not an alphabet, it returns False.

Let’s look at an example.

# create a string
s = "Bucky"
# check if string contains only alphabets
print(s.isalpha())

Output:

True

We get True as the output. This is because all the characters in the string s above are alphabets.

Let’s look at another example.

# create a string
s = "Bucky7"
# check if string contains only alphabets
print(s.isalpha())

Output:

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

False

Here, we get False as the output. This is because not all characters in the string s above are alphabets. One of the characters in the string, “7” is a digit.

Also, be careful if you’re string contains any punctuations. For example, for the string “you’re” the isalpha() function returns False.

# string with punctuations
s = "you're"
# check if string contains only alphabets
print(s.isalpha())

Output:

False

This is because not all characters in the string are alphabets. The character ' is not an alphabet.

Again, this is expected because the objective of the isalpha() function is to check if all the characters are alphabets or not.

For more on the string isalpha() function, refer to its documentation.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top