Imagine a string, like 'Agh#$%#%2341- -!zdrkfd' and I only wish to perform some operating on it such that only the lowercase letters are returned (as an example), which in this case would bring 'ghzdrkfd'.
How do you do this in Python? The obvious way would be to create a list, of characters, 'a' through 'z', then iterate over the characters in my string and build a new string, character by character, of those in my list only. This seems primitive.
I was wondering if regular expressions are appropriate. Replacing unwanted characters seems problematic and I tend to prefer whitelisting over blacklisting. The .match
function does not seem appropriate. I have looked over the appropriate page on the Python site, but have not found a method which seems to fit.
If regular expressions are not appropriate and the correct approach is looping, is there a simple function which "explodes" a string into a list? Or am I just hitting another for loop there?
I'd use a regex. For lowercase match [a-z].
Using a regular expression is easy enough, especially for this scenario:
If you plan on doing this many times, it is best to compile the regular expression before hand: