Python用函数的输出替换字符串模式

Python用函数的输出替换字符串模式

本文介绍了Python用函数的输出替换字符串模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Python 字符串,比如 快速的@red fox 跳过了@lame brown dog.

我正在尝试将每个以 @ 开头的单词替换为将单词作为参数的函数的输出.

def my_replace(match):返回匹配 + str(match.index('e'))#伪代码string = "快速的@red fox 跳过了@lame 棕色的狗."string.replace('@%match', my_replace(match))# 结果敏捷的@red2 狐狸跳过了@lame4 棕色狗."

有没有聪明的方法来做到这一点?

解决方案

你可以传递一个函数给 re.sub.该函数将接收一个匹配对象作为参数,使用 .group() 将匹配提取为字符串.

>>>def my_replace(match):... match = match.group()...返回匹配 + str(match.index('e'))...>>>string = 快速的@red fox 跳过了@lame brown 狗.">>>re.sub(r'@\w+', my_replace, 字符串)敏捷的@red2 狐狸跳过了@lame4 棕色的狗."

I have a string in Python, say The quick @red fox jumps over the @lame brown dog.

I'm trying to replace each of the words that begin with @ with the output of a function that takes the word as an argument.

def my_replace(match):
    return match + str(match.index('e'))

#Psuedo-code

string = "The quick @red fox jumps over the @lame brown dog."
string.replace('@%match', my_replace(match))

# Result
"The quick @red2 fox jumps over the @lame4 brown dog."

Is there a clever way to do this?

解决方案

You can pass a function to re.sub. The function will receive a match object as the argument, use .group() to extract the match as a string.

>>> def my_replace(match):
...     match = match.group()
...     return match + str(match.index('e'))
...
>>> string = "The quick @red fox jumps over the @lame brown dog."
>>> re.sub(r'@\w+', my_replace, string)
'The quick @red2 fox jumps over the @lame4 brown dog.'

这篇关于Python用函数的输出替换字符串模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 21:56