对具有多种类型空白字符的字符串中的每个单词应用函数的最pythonic 方法是什么? [英] What's the most pythonic way to apply a function on every word in a string with multiple types of white space characters?

查看:15
本文介绍了对具有多种类型空白字符的字符串中的每个单词应用函数的最pythonic 方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个函数

def f(a):返回一个[::-1]

我想将函数 f 应用于字符串中的每个单词.如果字符串只包含空格,我可以做

<预><代码>>>>s = '这是香蕉'>>>' '.join(map(f, s.split(' ')))'siht si a ananab '

但是当字符串由多种类型的空格组成时,我该怎么做呢?(例如,\t 和 \n)

比如我想改变

'\t \t 这是一个\tbanana \n'

'\t \t siht si a\tananab \n'

解决方案

使用正则表达式,re.sub() 函数 接受一个函数来进行替换.匹配非空白:

re.sub(r'[^\s]+', lambda m: f(m.group(0)), s)

函数传入一个匹配对象;使用 .group(0) 您可以提取匹配的文本并将其传递给您的函数.返回值用于替换输出字符串中的原始匹配文本.

演示:

<预><代码>>>>进口重新>>>定义 f(a):...返回一个[::-1]...>>>s = '\t \t 这是一个\tbanana \n'>>>re.sub(r'[^\s]+', lambda m: f(m.group(0)), s)'\t \t siht si a\tananab \n'

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'

这篇关于对具有多种类型空白字符的字符串中的每个单词应用函数的最pythonic 方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆