Suppose I have a function
def f(a):
return a[::-1]
I want to apply the function f to every word on a string. If the string consists only of s
Use a regular expression, the re.sub() function accepts a function to do the substitutions. Match non-whitespace instead:
re.sub(r'[^\s]+', lambda m: f(m.group(0)), s)
The function is passed a match object; using .group(0)
you can extract the matched text to pass it to your function. The return value is used to replace the original matched text in the output string.
Demo:
>>> import re
>>> def f(a):
... return a[::-1]
...
>>> s = '\t \t this is a\tbanana \n'
>>> re.sub(r'[^\s]+', lambda m: f(m.group(0)), s)
'\t \t siht si a\tananab \n'