- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
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.
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))
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.
In this article, we learned about using List comprehension and ord() function in Python to remove all characters other than alphabets.
- 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
- Python prorgam to remove duplicate elements index from other list
- Python – All replacement combination from other list
- Count set bits using Python List comprehension
- Convert list of strings and characters to list of characters in Python
- Python - Ways to initialize list with alphabets
- 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?
- How to catch a python exception in a list comprehension?