import re pat = re.compile('(?=([0-9]|one|two|three|four|five|six|seven|eight|nine))') def conv(s): if s in ('0'): return 0 elif s in ('1', 'one'): return 1 elif s in ('2', 'two'): return 2 elif s in ('3', 'three'): return 3 elif s in ('4', 'four'): return 4 elif s in ('5', 'five'): return 5 elif s in ('6', 'six'): return 6 elif s in ('7', 'seven'): return 7 elif s in ('8', 'eight'): return 8 elif s in ('9', 'nine'): return 9 else: raise RuntimeError() with open('adv01.txt') as f: t = f.readlines() sum = 0 for l in t: if l: matches = [m.group(1) for m in pat.finditer(l)] sum += conv(matches[0]) * 10 + conv(matches[-1]) print(sum)