What's The Most Pythonic Way To Apply A Function On Every Word In A String With Multiple Types Of White Space Characters?
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 = '
Solution 1:
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'
Solution 2:
Use regular expressions, where you can easily get whole words and also whole chunks of continuous whitespace.
Post a Comment for "What's The Most Pythonic Way To Apply A Function On Every Word In A String With Multiple Types Of White Space Characters?"