
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
List comprehension and ord() in Python to remove all characters other than alphabets
In this article, we will learn about a program in which we can remove an all characters other than alphabets using the concept of list comprehension and ord() function in Python 3.x. Or earlier.
Algorithm
1.We Traverse the given string to check the charater. 2.Selection of characters is done which lie in the range of either [a-z] or [A-Z]. 3.Using the join function we print all the characters which pass the test together.
Example
def remchar(input): # checking uppercase and lowercase characters final = [ch for ch in input if (ord(ch) in range(ord('a'),ord('z')+1,1)) or (ord(ch) in range(ord('A'),ord('Z')+1,1))] return ''.join(final) # Driver program if __name__ == "__main__": input = "Tutorials@point786._/?" print (remchar(input))
Output
Tutorialspoint
The ord() function accepts a character as an argument and returns back the corresponding ASCII value. This allows us in easy and quick comparison.
Here we also implemented list comprehension which allows us to filter all the necessary elements of a list and club them together with the help of join function to get the desired output.
Conclusion
In this article, we learned about using List comprehension and ord() function in Python to remove all characters other than alphabets.
- Related Articles
- C++ Program to Remove all Characters in a String Except Alphabets
- Python List Comprehension and Slicing?
- Python List Comprehension?
- Python – Remove characters greater than K
- Nested list comprehension in python
- Python - Remove all characters except letters and numbers
- Move all zeroes to end of the array using List Comprehension in Python
- How to remove a list of characters in string in Python?
- How to remove all special characters, punctuation and spaces from a string in Python?
- Python – Strings with all given List characters
- Convert list of strings and characters to list of characters in Python
- How to create a dictionary with list comprehension in Python?
- How to catch a python exception in a list comprehension?
- Count set bits using Python List comprehension
- K’th Non-repeating Character in Python using List Comprehension and OrderedDict

Advertisements