Filtering a String for a Set of Characters
this is from the 'python cookbook' but isn't explained that well.
allchars = string.maketrans('','')
def makefilter(keep):
delchars = allchars.translate(allchars, keep)
def thefilter(s):
return s.translate(allchars,delchars)
return thefilter
if __name__ == '__main__':
just_vowels = makefilter开发者_StackOverflow社区('aeiou')
print just_vowels('four score and seven years ago')
print just_vowels('tigere, igers, bigers')
my question is, how does thefilters 's' get passed in as a parameter?
makefilter
returns a function.
In the example code:
just_vowels = makefilter('aeiou')
the variable just_vowels
now refers to a function based on thefilter
.
The code:
print just_vowels('tigere, igers, bigers')
is calling that function, and setting its s
parameter to the string 'tigere, igers, bigers'
.
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'
精彩评论