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 spaces, I can do
>>> s = ' this is a banana '
>>> ' '.join(map(f, s.split(' ')))
' siht si a ananab '
But how can I do this when the string consists of multiple types of white spaces? (e.g., \t and \n)
For example, I want to change
'\t \t this is a\tbanana \n'
to
'\t \t siht si a\tananab \n'
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'
Use regular expressions, where you can easily get whole words and also whole chunks of continuous whitespace.