Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Check Whether String Contains Only Numbers or Not - Python
Next article icon

Python | Ways to check if given string contains only letter

Last Updated : 30 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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")
 
 
Output
Initial String ababababa String contains only letters

Time complexity: O(n), where n is length of ini_str.
Auxiliary Space: O(1)

  
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")
 
 
Output
Initial String ababababa Contains only letters

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #3 : Without any builtin methods

Python3




# Python code to demonstrate
# to find whether string contains
# only letters
 
# Initialising string
ini_str = "ababababa"
lowerletters="abcdefghijklmnopqrstuvwxyz"
upperletters="ABCDEFGIJKLMNOPQRSTUVWXYZ"
a=lowerletters+upperletters
# Printing initial string
print ("Initial String", ini_str)
c=0
for i in ini_str:
    if i in a:
        c+=1
if(c==len(ini_str)):
    print("String contains only letters")
else:
    print("String doesn't contains only letters")
 
 
Output
Initial String ababababa String contains only letters

Method #4: Using operator.countOf() method

Python3




import operator as op
# Python code to demonstrate
# to find whether string contains
# only letters
 
# Initialising string
ini_str = "ababababa"
lowerletters = "abcdefghijklmnopqrstuvwxyz"
upperletters = "ABCDEFGIJKLMNOPQRSTUVWXYZ"
a = lowerletters+upperletters
# Printing initial string
print("Initial String", ini_str)
c = 0
for i in ini_str:
    if op.countOf(a, i):
        c += 1
if(c == len(ini_str)):
    print("String contains only letters")
else:
    print("String doesn't contains only letters")
 
 
Output
Initial String ababababa String contains only letters

Time Complexity: O(N)

Auxiliary Space : O(1)

Method#5: Using Ord() method. 

Approach: For each character, we use the ord() method to get the ASCII value of the character. Then we check if the ASCII value is within the range of ASCII values for uppercase and lowercase letters (65-90 and 97-122 respectively). If the ASCII value is not within these ranges, it means that the character is not a letter, and the code prints “String doesn’t contains only letters” and breaks out of the loop. If the loop completes without breaking, it means all the characters in the string are letters, and the code prints “String contains only letters”.

Python3




# Using ord() method to find whether string contains only letters
 
# Initialising string
ini_str = "ababababa"
 
# Printing initial string
print ("Initial String", ini_str)
 
# Iterating through each character in the string
for char in ini_str:
    # Using ord() method to get the ASCII value of the character
    ascii_val = ord(char)
    # If the ASCII value is not between 65 and 90 or 97 and 122 (ASCII values of uppercase and lowercase letters)
    if not (ascii_val >= 65 and ascii_val <= 90) and not (ascii_val >= 97 and ascii_val <= 122):
        print("String doesn't contains only letters")
        break
else:
    print("String contains only letters")
#this code contributed by tvsk
 
 
Output
Initial String ababababa String contains only letters

Time Complexity: O(N)

Auxiliary Space : O(1)



Next Article
Check Whether String Contains Only Numbers or Not - Python
author
garg_ak0109
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Check Whether String Contains Only Numbers or Not - Python
    We are given a string s="12345" we need to check whether the string contains only number or not if the string contains only number we will return True or if the string does contains some other value then we will return False. This article will explore various techniques to check if a string contains
    3 min read
  • Python - Check if String contains any Number
    We are given a string and our task is to check whether it contains any numeric digits (0-9). For example, consider the following string: s = "Hello123" since it contains digits (1, 2, 3), the output should be True while on the other hand, for s = "HelloWorld" since it has no digits the output should
    2 min read
  • How to Check If a String is Empty or Contains Whitespaces in Python
    Sometimes, we must check if a string is empty or only contains Whitespaces. This check is useful when we are processing user input or handling data. Another simple way to check if a string is empty is by using the len() function. This checks the length of the string. [GFGTABS] Python s = "
    1 min read
  • Python program to check if given string is vowel Palindrome
    Given a string (may contain both vowel and consonant letters), remove all consonants, then check if the resulting string is palindrome or not. Examples: Input : abcuhuvmnba Output : YES Explanation : The consonants in the string "abcuhuvmnba" are removed. Now the string becomes "auua". Input : xayzu
    5 min read
  • Python program to check if given string is pangram
    The task is to check if a string is a pangram which means it includes every letter of the English alphabet at least once. In this article, we’ll look at different ways to check if the string contains all 26 letters. Using Bitmasking Bitmasking uses a number where each bit represents a letter in the
    3 min read
  • Python - Test if string contains element from list
    Testing if string contains an element from list is checking whether any of the individual items in a list appear within a given string. Using any() with a generator expressionany() is the most efficient way to check if any element from the list is present in the list. [GFGTABS] Python s = "Pyth
    3 min read
  • Python program to check if lowercase letters exist in a string
    Checking for the presence of lowercase letters involves scanning the string and verifying if at least one character is a lowercase letter (from 'a' to 'z'). Python provides simple and efficient ways to solve this problem using built-in string methods and constructs like loops and comprehensions. Usi
    2 min read
  • Python program to check if a given string is Keyword or not
    This article will explore how to check if a given string is a reserved keyword in Python. Using the keyword We can easily determine whether a string conflicts with Python's built-in syntax rules. Using iskeyword()The keyword module in Python provides a function iskeyword() to check if a string is a
    2 min read
  • Python - Ways to Count Number of Substring in String
    Given a string s, determine the number of substrings that satisfy certain criteria. For example we are given a string s="hellohellohello" we need to count how many time the substring occur in the given string suppose we need to find the substring "hello" so that the count becomes 3. We can use metho
    2 min read
  • Check if string contains character - Python
    We are given a string and our task is to check if it contains a specific character, this can happen when validating input or searching for a pattern. For example, if we check whether 'e' is in the string 'hello', the output will be True. Using in Operatorin operator is the easiest way to check if a
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences