This is a simple example:
import re math=\'3+5\' print re.sub(r\'<(.)>(\\d+?)\\+(\\d+?)\\1>\', int(r\'\\2\') + int(r\'\\3\'
You need to use lambda function.
print re.sub(r'<(.)>(\d+?)\+(\d+?)\1>', lambda m: str(int(m.group(2)) + int(m.group(3))), math)