CLOSE

   Python  String Handling  How To  
   Technology    Programming

How to Extract Alphabets from a given String in Python

           
 APRIL 15, 2019   by hafeezulkareem

In this tutorial, we are going to learn how to extract only characters from any given string in python. We will learn two different ways of doing so using the following two method:

  1. ord(char)
  2. chr.isalpha()



Using ord(char)

  • Get the input from the user using the input() method.
  • Declare an empty string to store the alphabets.
  • Loop through the string:
    • If the ASCII value of char is between 65 and 90 or 97 and 122. Use the ord() method for the ASCII values of chars.
      • Add it to the empty string
  • Print the resultant string.
## getting the input from the user
string = input("Enter a string: ")

## initializing a new string to apppend only alphabets
only_alpha = ""

## looping through the string to find out alphabets
for char in string:

## ord(chr) returns the ascii value
## CHECKING FOR UPPER CASE
if ord(char) >= 65 and ord(char) <= 90:
only_alpha += char
## checking for lower case
elif ord(char) >= 97 and ord(char) <= 122:
only_alpha += char

## printing the string which contains only alphabets
print(only_alpha)

Input:

Enter a string: study123tonight

Output of the program:

studytonight



Using chr.isalpha()

  • Get the input from the user using the input() method.
  • Declare an empty string to store the alphabets.
  • Loop through the string:
    • Check whether the char is an alphabet or not using chr.isalpha() method.
      • Add it to the empty string.
  • Print the resultant string.
## get the input from the user
string = input("Enter a string: ")

## initializing a new string to append only alphabets
only_alpha = ""

## looping through the string to find out alphabets
for char in string:

## checking whether the char is an alphabet or not using chr.isalpha() method
if char.isalpha():
only_alpha += char

## printing the string which contains only alphabets
print(only_alpha)

Input:

Enter a string: study123tonight

Output of the program:

studytonight

If you have any queries regarding the programs, please let me know in the comment section below.


SHARE YOUR THOUGHTS WITH US!