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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 whther string contains only number
if ini_str.isalpha():
    print("String contains only letters")
else:
    print("String doesn't contains only letters")

chevron_right


 
Method #2: Using re

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 whther 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")

chevron_right




My Personal Notes arrow_drop_up

Programming freaktech Enthusiast and have interest in learning new upcoming technologies

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.