How do you only keep the alphabet in python?

What is the best way to remove all characters from a string that are not in the alphabet? I mean, remove all spaces, interpunction, brackets, numbers, mathematical operators..

For example:

input: 'as32{ vd"s k!+'
output: 'asvdsk'

asked Dec 11, 2015 at 0:16

0

You could use re, but you don't really need to.

>>> s = 'as32{ vd"s k!+'
>>> ''.join(x for x in s if x.isalpha())
'asvdsk'    
>>> filter(str.isalpha, s) # works in python-2.7
'asvdsk'
>>> ''.join(filter(str.isalpha, s)) # works in python3
'asvdsk'

answered Dec 11, 2015 at 0:19

How do you only keep the alphabet in python?

timgebtimgeb

74.5k20 gold badges114 silver badges139 bronze badges

If you want to use regular expression, This should be quicker

import re
s = 'as32{ vd"s k!+'
print re.sub('[^a-zA-Z]+', '', s)

prints 'asvdsk'

answered Dec 11, 2015 at 0:26

How do you only keep the alphabet in python?

nehemnehem

11.4k6 gold badges53 silver badges78 bronze badges

Here is a method that uses ASCII ranges to check whether an character is in the upper/lower case alphabet (and appends it to a string if it is):

s = 'as32{ vd"s k!+'
sfiltered = ''

for char in s:
    if((ord(char) >= 97 and ord(char) <= 122) or (ord(char) >= 65 and ord(char) <= 90)):
        sfiltered += char

The variable sfiltered will show the result, which is 'asvdsk' as expected.

answered Dec 11, 2015 at 0:36

How do you only keep the alphabet in python?

Patrick YuPatrick Yu

9421 gold badge7 silver badges19 bronze badges

This simple expression get all letters, including non ASCII letters ok t áàãéèêçĉ... and many more used in several languages.

r"[^\W\d]+"

It means "get a sequence of one or more characters that are not either "non word characters" or a digit.

answered Apr 28 at 3:16

plpsanchezplpsanchez

1853 silver badges10 bronze badges

If you'd like to preserve characters like áàãéèêçĉ that are used in many languages around thw world, try this:

import re
print re.sub('[\W\d_]+', yourString)

answered Jun 2 at 14:36

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

How do you input only the alphabet in Python?

To only allow letters when taking user input: Use a while loop to iterate until the user enters only letters. Use the str. isalpha() method to check if the user entered only letters.

How do you store alphabets in Python?

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. ascii_uppercase instances.

How do you filter only the alphabet of a string in Python?

Using 'isalpha()' It returns True if it contains only the alphabet. It'll iterate through the string and check whether each character in the string is an alphabet or not and return it if it's an alphabet. It's a generator expression. It returns a generator object containing all alphabets from the string.

How do I extract letters from a word in Python?

Extract a substring from a string in Python (position, regex).
Extract a substring by specifying the position and number of characters. Extract a character by index. ... .
Extract a substring with regular expressions: re.search() , re.findall().
Regular expression pattern examples. Wildcard-like patterns..