简体   繁体   English

在具有多种类型的空白字符的字符串中的每个单词上应用函数的最有效的方法是什么?

[英]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. 我想将函数f应用于字符串上的每个单词。 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? 但是,当字符串包含多种类型的空格时,该怎么办? (eg, \\t and \\n) (例如\\ t和\\ 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. 使用正则表达式, re.sub()函数接受一个函数进行替换。 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. 使用.group(0)您可以提取匹配的文本以将其传递给函数。 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'

使用正则表达式,您可以在其中轻松获得整个单词以及连续空白的整个块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM