How to take only alphabets as input in python

I'm a technical writer learning python. I wanted to write a program for validating the Name field input,as a practise, restricting the the user entries to alphabets.I saw a similar code for validating number (Age)field here, and adopted it for alphabets as below:

import string

import re

r = re.compile(r'[a-zA-Z]+') 
print "WELCOME FOR NAME VERIFICATION. TYPE ALPHABETS ONLY!"
print raw_input("Your Name:")
x = r
if x == r:
    print x
elif x != r:
    print "Come on,'", x,"' can't be your name"
    print raw_input("Your Name:")
if 5<=len(x)<=10:
    print "Hi,", x, "!"
elif len(x)>10:
    print "Mmm,Your name is too long!"
elif len(x)<5:
    print "Alas, your name is too short!"

raw_input("Press 'Enter' to exit!")

I intend this code block to do two things. Namely, display the input prompt until the user inputs alphabets only as 'Name'. Then, if that happens, process the length of that input and display messages as coded. But, I get two problems that I could not solve even after a lot of attempts. Either, even the correct entries are rejected by exception code or wrong entries are also accepted and their length is processed.

Please help me to debug my code. And, is it possible to do it without using the reg exp?

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.

You may also like:

  • Python Tkinter Label Widget
  • Python Relational and Logical Operators
  • Basics of Object-Oriented Programming
  • Python NumPy Data Types

In this tutorial, we will look at how to keep only letters (extract alphabets) from a string in Python with the help of examples.

How to extract only alphabets from a string in Python?

How to take only alphabets as input in python

You can use a regular expression to extract only letters (alphabets) from a string in Python. You can also iterate over the characters in a string and using the string isalpha() function to keep only letters in a string.

Let’s look at both the methods with the help of examples –

Extract alphabets from a string using regex

You can use the regular expression 'r[^a-zA-Z]' to match with non-alphabet characters in the string and replace them with an empty string using the re.sub() function. The resulting string will contain only letters.

Let’s look at an example.

import re

# string with letters, numbers, and special characters
s = "[email protected]"
# keep only letters
res = re.sub(r'[^a-zA-Z]', '', s)
print(res)

Output:

BuckyBarnes

You can see that the resulting string contains only letters.

Using string isalpha() function

Alternatively, you can use the string isalpha() function to remove non-alphabet characters from the string. Use the following steps –

  1. Create an empty string to store our result string with only letters.
  2. Iterate through each character in our given string.
  3. For each character, check if its an alphabet using the string isalpha() function. If it is, then add the character to our result string.

Let’s look at an example.

# string with letters, numbers, and special characters
s = "[email protected]"
# keep only letters
res = ""
for ch in s:
    if ch.isalpha():
        res += ch
print(res)

Output:

BuckyBarnes

The result string contains only letters from the original string.

The above code can be reduced to fewer lines using list comprehension.

# string with letters, numbers, and special characters
s = "[email protected]"
# keep only letters
res = "".join([ch for ch in s if ch.isalpha()])
print(res)

Output:

BuckyBarnes

We get the same result as above.

You might also be interested in –

  • Python – Check If String Contains Only Letters
  • Python – Remove Non Alphanumeric Characters from String
  • Remove Substring From a String in Python


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

  • Piyush is a data scientist passionate about using data to understand things better and make informed decisions. In the past, he's worked as a Data Scientist for ZS and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

    View all posts

How do you input a letter in Python?

To get user input in Python (3), the command you use is input() . Store the result in a variable, and use it to your heart's content. Remember that the result you get from the user will be a string, even if they enter a number.

How do you check only the alphabet in Python?

Use str. isalpha() to check if a string contains only letters Call str. isalpha() with str as the string to be checked to return True if all characters in str are alphabetic and False otherwise.

Can we import alphabets in Python?

The string module is part of the standard Python library, meaning you don't need to install anything. The easiest way to load a list of all the letters of the alphabet is to use the string. ascii_letters , string. ascii_lowercase , and string.