Passing a function to re.sub in Python

You should call group() to get the matching string:

import re

number_mapping = {'1': 'one',
                  '2': 'two',
                  '3': 'three'}
s = "1 testing 2 3"

print re.sub(r'\d', lambda x: number_mapping[x.group()], s)

prints:

one testing two three

A solution without lambda

import re

def convert_func(matchobj):
    m =  matchobj.group(0)
    map = {'7': 'seven',
           '8': 'eight',
           '9': 'nine'}
    return map[m]

line = "7 ate 9"
new_line =  re.sub("[7-9]", convert_func, line)

To make your function fit with re.sub, you can wrap it with a lambda:

re.sub('pattern', lambda m: myfunction(m.group()), 'text')

Tags:

Python

Regex