Python | Ways to check if given string contains only letter
Given a string, write a Python program to find whether a string contains only letters and no other keywords. Let’s discuss a few methods to complete the task.
Method #1: Using isalpha() method
Python3
# Python code to demonstrate# to find whether string contains# only letters# Initialising stringini_str = "ababababa"# Printing initial stringprint ("Initial String", ini_str)# Code to check whether string contains only numberif ini_str.isalpha(): print("String contains only letters")else: print("String doesn't contains only letters") |
Method #2: Using re
Python3
# Python code to demonstrate# to find whether string contains# only lettersimport re# Initialising stringini_str = "ababababa"# Printing initial stringprint ("Initial String", ini_str)# Code to check whether string contains only numberpattern = re.compile("^[a-zA-Z]+$")if pattern.match(ini_str): print ("Contains only letters")else: print ("Doesn't contains only letters") |
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course


