The following code creates a filtering functor for a given character set, that can then be used on any number of strings.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
def makefilter(keep): """ Return a functor that takes a string and returns a copy of that string consisting of only the characters in 'keep'. """ import string # make a string of all chars, and one of all those NOT in 'keep' allchars = string.maketrans('', '') delchars = ''.join([c for c in allchars if c not in keep]) # return the functor return lambda s,a=allchars,d=delchars: s.translate(a, d) import string identifier = makefilter(string.letters + string.digits + '_') print identifier(string.maketrans('', ''))
Splitting the task into a preparation phase and an execution part drastically improves runtime efficiency. First, we build the needed strings and store them in a functor. Then, we can use the functor to actually filter some strings.
Another important thing to note is that the functor uses the built-in translate() function and is thus very fast, after the two helper strings are created, which happens only once.