我在Python中有一个字符串 The quick @red fox jumps over the @lame brown dog.
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."
有聪明的方法吗?
您可以将函数传递给re.sub。该函数将接收一个match对象作为参数,用于.group()将匹配提取为字符串。
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.'