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.