List comprehension and ord () in Python to remove all characters except alphabets

Python Methods and Functions

If a string consisting of alphabets and other characters is given, remove all characters except alphabets and print the generated string. 
Examples:

 Input: str = "$ Gee * k; s..fo, r'Ge ^ eks?" Output: Python.Engineering 

This problem has an existing solution, please refer to List Comphetsion
Approach: yes

 1. Traverse string 2. Select characters which lie in range of [az] or [AZ] 3. Print them together 

How do ord () and range () functions in python?

  • The ord () method returns an integer that represents the Unicode code point of the given Unicode character.  For example ,
     ord ('5') = 53 and ord (' A') = 65 and ord ('$') = 36 

  • The range (a, b, step) function generates a list of elements that ranges from inclusive to exclusive b, increasing / decreasing the given step.

# Python code to remove all characters
# except alphabets from string

 

def removeAll ( input ):

  

# Pass the full line and separate

# all characters between [az] or [AZ]

  sepChars = [char for char in input if  

ord (char) in range ( ord ( 'a' ), ord ( 'z' ) + 1 , 1 ) or ord (char) in  

 range ( ord ( ' A' ), ord ( 'Z' ) + 1 , 1 )]

 

# concatenate all delimited characters

# and print them together

return ' '.join (sepChars)

 
# Driver program

if __ name__ = = "__ main__" :

input = "$ Gee * k; s..fo, r'Ge ^ eks?"

print removeAll ( input )

Output:

 Python.Engineering 




Tutorials