#!/usr/bin/python import re with open('03a.txt') as f: text = f.read() reg = re.compile(r'mul\((?P[0-9]+),(?P[0-9]+)\)') total = 0 for match in reg.finditer(text): total += int(match.group('num1')) * int(match.group('num2')) print(total)