我在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."
有一种聪明的方法吗?
答案 0 :(得分:82)
您可以将功能传递给re.sub
。该函数将接收匹配对象作为参数,使用.group()
将匹配作为字符串提取。
>>> def my_replace(match):
... match = match.group()
... return match + str(match.index('e'))
...
>>> re.sub(r'@\w+', my_replace, string)
'The quick @red2 fox jumps over the @lame4 brown dog.'
答案 1 :(得分:6)
我不知道你可以将一个函数传递给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.
这个简单的例子要求所有捕获组都存在(没有可选组)。
答案 2 :(得分:3)
尝试:
import re
match = re.compile(r"@\w+")
items = re.findall(string)
for item in items:
string = string.replace(item, my_replace(item)
这将允许您使用函数的输出替换以@开头的任何内容。 如果你需要这个功能的帮助我也不是很清楚。如果是这种情况,请告诉我
答案 3 :(得分:1)
一个带有正则表达式并缩减的短篇小说:
>>> 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.'