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
Selected Reading
Python - Remove all characters except letters and numbers
When it is required to remove all characters except for letters and numbers, regular expressions are used. A regular expression is defined, and the string is subjected to follow this expression.
Using Regular Expressions with re.sub()
The re.sub() function replaces all non-alphanumeric characters with an empty string ?
import re
my_string = "python123:, .@! abc"
print("The string is:")
print(my_string)
result = re.sub('[\W_]+', '', my_string)
print("The expected string is:")
print(result)
The output of the above code is ?
The string is: python123:, .@! abc The expected string is: python123abc
Using isalnum() with List Comprehension
An alternative approach uses the isalnum() method to filter characters ?
my_string = "python123:, .@! abc"
print("The string is:")
print(my_string)
result = ''.join([char for char in my_string if char.isalnum()])
print("The filtered string is:")
print(result)
The string is: python123:, .@! abc The filtered string is: python123abc
Using filter() with isalnum()
The filter() function provides a functional programming approach ?
my_string = "python123:, .@! abc"
print("The string is:")
print(my_string)
result = ''.join(filter(str.isalnum, my_string))
print("The filtered string is:")
print(result)
The string is: python123:, .@! abc The filtered string is: python123abc
Comparison
| Method | Performance | Readability | Best For |
|---|---|---|---|
re.sub() |
Fast for large strings | Good | Complex patterns |
| List comprehension | Good | Very good | Simple filtering |
filter() |
Good | Good | Functional style |
Conclusion
Use re.sub() for complex pattern matching or large strings. For simple alphanumeric filtering, list comprehension with isalnum() is more readable and efficient.
Advertisements
