What's the most pythonic way to apply a function on every word in a string with multiple types of white space characters?

前端 未结 2 652
误落风尘
误落风尘 2021-01-24 11:04

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

相关标签:
2条回答
  • 2021-01-24 11:34

    Use regular expressions, where you can easily get whole words and also whole chunks of continuous whitespace.

    0 讨论(0)
  • 2021-01-24 11:55

    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'
    
    0 讨论(0)
提交回复
热议问题