How to only accept letters in python

I'm having trouble getting my input to accept only a-z and A-Z letters. This is what I came up with

        while(not(studentName == "END")):
    studentName = input("What is the name of the student (END to finish) ")
    if not re.match("^[a-z]*$", studentName):
        print("Only letters are allowed")
    elif len(studentName) == 0:
        print("Insufficient characters. Please try again.")
    else:
        studentsNames.append(studentname)

However I just come up with an error "re not defined". What do I do :C

asked Jun 23, 2015 at 5:46

How to only accept letters in python

2

Instead of using regular expressions, I like to use the built-in string methods. One of these is str.isalpha(), which, when called on a string, returns True if the string contains only A-z. So instead of:

if not re.match("^[a-z]*$", studentName):
    print("Only letters are allowed")

I'd just write:

if not studentName.isalpha():
    print("Only letters are allowed!")

answered Jun 23, 2015 at 5:55

jmejme

18.8k5 gold badges38 silver badges39 bronze badges

You need to import re module and you must need to change your regex as,

if not re.match(r"^[A-Za-z]+$", studentName):

Just type the below code at the top of your python script.

import re

Your regex "^[a-z]*$" would match zero or more lowercase letters. That is, it would match empty strings also and it won't match the string with only uppercase letters like FOO.

So this if not re.match("^[a-z]*$", studentName): will return true for all the strings which must not be an empty string or the string which contains only lowercase letters.

answered Jun 23, 2015 at 5:48

How to only accept letters in python

Avinash RajAvinash Raj

169k25 gold badges214 silver badges262 bronze badges

7

You could use a set, and string.ascii_letters:

from string import ascii_letters

def is_all_characters(student_name):
    return set(student_name) in set(ascii_letters)

answered Jun 23, 2015 at 6:00

How to only accept letters in python

Peter WoodPeter Wood

23.2k5 gold badges58 silver badges94 bronze badges

isalpha() works for this requirement.

username = input("Enter Username: ")
if username.isalpha() is False:
 print("Only Text allowed in Username")
else:
 print("Welcome "+username)

answered Mar 6, 2021 at 7:03

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 only accept letters 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 make input only accept string in Python?

input() always returns a string, so you can try these methods:.
METHOD 1. Use isalpha(). ... .
METHOD 2. Try to convert it to a integer or float, and print the message if it is possible. ... .
METHOD 3. Go through the name, character by character, and check if it is a type int (integer) or float..

How do you input letters in Python?

Using chr..
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..

How do you accept text in Python?

The input() function: Use the input() function to get Python user input from keyboard. Press the enter key after entering the value. The program waits for user input indefinetly, there is no timeout.