It's possible to simplify that cookbook code using a list comprehension or generator expression:
def make_filter(keep):
def the_filter(string):
return ''.join(char for char in string if char in keep)
return the_filter
This will work the same way as the provided makefilter.
>>> just_vowels = make_filter('aeiou')
>>> just_vowels('four score and seven years ago')
'ouoeaeeeaao'
>>> just_vowels('tigere, igers, bigers')
'ieeieie'
Like Richie explained, it will dynamically create a function, which you can later call on a string. The (char for char in string if char in keep)
bit of code creates a generator which will iterate over the characters of the original string and perform the filtering. ''.join(...)
then combines those characters back into a string.
Personally, I find that level of abstraction (writing a function to return a function) to be overkill for this sort of problem. It's a question of taste, but I think your code would be clearer if you just call the significant line directly:
>>> string = 'tigere, igers, bigers'
>>> keep = 'aeiou'
>>> ''.join(char for char in string if char in keep)
'ieeieie'