Skip to content
Related Articles

Related Articles

Python | Ways to check if given string contains only letter

View Discussion
Improve Article
Save Article
Like Article
  • 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")

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!