Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
List comprehension and ord() in Python to remove all characters other than alphabets
In this article, we will learn how to remove all non-alphabetic characters from a string using list comprehension and the ord() function in Python. This approach filters characters by checking their ASCII values.
Algorithm
The algorithm follows these steps:
1. Traverse the given string to check each character 2. Select characters that lie in the range [a-z] or [A-Z] using ord() 3. Use join() function to combine all valid characters into a string
Understanding ord() Function
The ord() function accepts a character as an argument and returns its corresponding ASCII value. This allows easy comparison with ASCII ranges ?
print("ASCII value of 'a':", ord('a'))
print("ASCII value of 'z':", ord('z'))
print("ASCII value of 'A':", ord('A'))
print("ASCII value of 'Z':", ord('Z'))
ASCII value of 'a': 97 ASCII value of 'z': 122 ASCII value of 'A': 65 ASCII value of 'Z': 90
Implementation Using List Comprehension
Here's the complete implementation that removes all non-alphabetic characters ?
def remchar(input_string):
# checking uppercase and lowercase characters
final = [ch for ch in input_string 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_string = "Tutorials@point786._/?"
print(remchar(input_string))
Tutorialspoint
Alternative Approaches
Using isalpha() Method
Python provides a simpler approach using the built-in isalpha() method ?
def remchar_simple(input_string):
return ''.join([ch for ch in input_string if ch.isalpha()])
# Test the function
input_string = "Hello123World!@#"
print(remchar_simple(input_string))
HelloWorld
How It Works
The list comprehension approach works by:
- Iterating through each character in the input string
- Checking if the character's ASCII value falls within alphabetic ranges
- Filtering only valid alphabetic characters
- Joining the filtered characters back into a string
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
ord() + range |
Medium | Good | Learning ASCII concepts |
isalpha() |
High | Better | Production code |
Conclusion
List comprehension with ord() provides a clear way to filter alphabetic characters by checking ASCII ranges. While isalpha() is simpler, understanding the ord() approach helps grasp character encoding concepts in Python.
