The Wayback Machine - https://web.archive.org/web/20220128061358/https://www.geeksforgeeks.org/python-ways-to-check-if-given-string-contains-only-letter/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python | Ways to check if given string contains only letter

  • Last Updated : 21 Jul, 2021

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 string
ini_str = "ababababa"
 
# Printing initial string
print ("Initial String", ini_str)
 
# Code to check whether string contains only number
if 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 letters
import re
 
# Initialising string
ini_str = "ababababa"
 
# Printing initial string
print ("Initial String", ini_str)
 
# Code to check whether string contains only number
pattern = 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


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!