Honestly, I would write it the way you wrote it, but if you want to do it "functionally" you probably need to use functools.reduce
, as you need to "reduce" a list of substitutions into a single result:
import functools
expr = '9subtract5equal4'
# a list of our replacements, as pairs
REPLACEMENTS = [
('subtract', '-'),
('plus', '+'),
('equal', '=='),
]
result = functools.reduce(
lambda word, old_new: word.replace(old_new[0], old_new[1]),
REPLACEMENTS,
expr
)
Here we just "accumulate" the results of the lambda function, which takes the last "accumulated" word and a substitution pair, and calls .replace()
to get the next "accumulated" word.
But really this is not a Pythonic way to solve this problem (there is a reason why reduce
got shoved into functools
in Python 3), and your original approach is better.