将函数应用于具有多种类型的白色 space 字符的字符串中的每个单词的最 pythonic 方法是什么?
What's the most pythonic way to apply a function on every word in a string with multiple types of white space characters?
假设我有一个函数
def f(a):
return a[::-1]
我想将函数 f 应用于字符串中的每个单词。如果字符串只包含空格,我可以做
>>> s = ' this is a banana '
>>> ' '.join(map(f, s.split(' ')))
' siht si a ananab '
但是当字符串由多种类型的空格组成时,我该怎么办呢? (例如,\t 和 \n)
比如我要改
'\t \t this is a\tbanana \n'
至
'\t \t siht si a\tananab \n'
使用正则表达式,您可以轻松获得整个单词以及整块连续空白。
使用正则表达式,re.sub()
function 接受一个函数来进行替换。匹配 非空白 而不是:
re.sub(r'[^\s]+', lambda m: f(m.group(0)), s)
函数被传递了一个match object;使用 .group(0)
您可以提取匹配的文本以将其传递给您的函数。 return 值用于替换输出字符串中的原始匹配文本。
演示:
>>> 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'
假设我有一个函数
def f(a):
return a[::-1]
我想将函数 f 应用于字符串中的每个单词。如果字符串只包含空格,我可以做
>>> s = ' this is a banana '
>>> ' '.join(map(f, s.split(' ')))
' siht si a ananab '
但是当字符串由多种类型的空格组成时,我该怎么办呢? (例如,\t 和 \n)
比如我要改
'\t \t this is a\tbanana \n'
至
'\t \t siht si a\tananab \n'
使用正则表达式,您可以轻松获得整个单词以及整块连续空白。
使用正则表达式,re.sub()
function 接受一个函数来进行替换。匹配 非空白 而不是:
re.sub(r'[^\s]+', lambda m: f(m.group(0)), s)
函数被传递了一个match object;使用 .group(0)
您可以提取匹配的文本以将其传递给您的函数。 return 值用于替换输出字符串中的原始匹配文本。
演示:
>>> 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'