I would like to apply a list of functions fs = [ f, g, h ]
sequentially to a string text=' abCdEf '
Something like f( g( h( text) ) )
.
This could easily be accomplished with the following code:
# initial text
text = ' abCDef '
# list of functions to apply sequentially
fs = [str.rstrip, str.lstrip, str.lower]
for f in fs:
text = f(text)
# expected result is 'abcdef' with spaces stripped, and all lowercase
print(text)
It seems that functools.reduce
should do the job here, since it "consumes" the list of functions at each iteration.
from functools import reduce
# I know `reduce` requires two arguments, but I don't even know
# which one to chose as text of function from the list
reduce(f(text), fs)
# first interaction should call
y = str.rstrip(' abCDef ') --> ' abCDef'
# next iterations fails, because tries to call ' abCDef'() -- as a function
Unfortunately, this code doesn't work, since each iteration returns a string istead of a function, and fails with TypeError
: 'str' object is not callable
.
map
, reduce
or list comprehension
to this problem?reduce
can take three arguments:
reduce(function, iterable, initializer)
What are these three arguments in general?
function
is a function of two arguments. Let's call these two arguments t
and f
.t
, will start as initializer
; then will continue as the return value of the previous call of function
.f
, is taken from iterable
.What are these three arguments in our case?
f
is going to be one of the functions;t
must be the text;function
must be the resulting text;function(t, f)
must be f(t)
.Finally:
from functools import reduce
# initial text
text = ' abCDef '
# list of functions to apply sequentially
fs = [str.rstrip, str.lstrip, str.lower]
result = reduce(lambda t,f: f(t), fs, text)
print(repr(result))
# 'abcdef'