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

我有一个 Python 中的字符串,比如 The quick @red fox jumps over the @lame brown dog.

我试图用一个函数的输出替换以 @开头的每个单词,该函数将这个单词作为参数。

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."

有什么聪明的办法吗?

35404 次浏览

试试:

import re


match = re.compile(r"@\w+")
items = re.findall(match, string)
for item in items:
string = string.replace(item, my_replace(item)

这将允许您用函数的输出替换以@开头的任何内容。 我不是很清楚,如果你需要帮助的功能,以及。让我知道,如果是这样的情况

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

>>> 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.'

一个带有 regex 和 reduce 的简短版本:

>>> import re
>>> pat = r'@\w+'
>>> reduce(lambda s, m: s.replace(m, m + str(m.index('e'))), re.findall(pat, string), string)
'The quick @red2 fox jumps over the @lame4 brown dog.'

我也不知道可以把函数传递给 re.sub()。重复@Janne Karila 解决我的一个问题的答案,这种方法也适用于多个捕获组。

import re


def my_replace(match):
match1 = match.group(1)
match2 = match.group(2)
match2 = match2.replace('@', '')
return u"{0:0.{1}f}".format(float(match1), int(match2))


string = 'The first number is 14.2@1, and the second number is 50.6@4.'
result = re.sub(r'([0-9]+.[0-9]+)(@[0-9]+)', my_replace, string)


print(result)

产出:

The first number is 14.2, and the second number is 50.6000.

这个简单的示例要求存在所有捕获组(没有可选的组)。