Stripping Non-Alphanumeric Characters in Python
In Python, removing non-alphanumeric characters from a string requires a slightly different approach compared to PHP.
Pythonic Methods
For a truly "Pythonic" solution, consider the following methods:
Alternative Approaches
For performance considerations, other methods may be faster:
Performance Benchmarking
Here are timing results for various methods, using the string.printable string:
Method | Time (μs/loop) |
---|---|
Join alphanumeric | 57.6 |
Filter alphanumeric | 37.9 |
Regex substitution with [W_] | 27.5 |
Regex substitution with [W_] | 15 |
Regex substitution with pattern.sub() | 11.2 |
The timings show that using the precompiled regular expression with pattern.sub() is the fastest method.
The above is the detailed content of How to Efficiently Strip Non-Alphanumeric Characters in Python?. For more information, please follow other related articles on the PHP Chinese website!