Technology3 min read

How to Extract Alphabets from a given String in Python

Abhishek Ahlawat

By Abhishek Ahlawat — Recently

Founder of StudyTonight and a MERN fullstack developer. Writes about JavaScript, web development, Linux, and tech.

Summarize this article using AI

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!



Spotted something outdated or wrong?

Liked this? See more StudyTonight posts in Google results.

Add StudyTonight as a preferred source
Next questLIVE OPSStep 2 / 3

Practice real incidents in the browser

System Design Ops — put out fires, ship fixes, and stack XP. Reading done. Time to play.

Play System Design
  • +XP

    Every sim

  • Incidents

    Live ops

  • Ranks

    Climb up

Read next