python

Passing a Function as a Callback to re sub in Python

As an advanced usage example of the "re sub" library and function method in the Python programming language, there is a technique of passing a function as a callback to perform processing. This enables advanced replacement processing that cannot be done with just normal regular expression replacement processing.

Shou Arisaka
1 min read
Nov 10, 2025

As an advanced usage example of the “re sub” library and function method in the Python programming language, there is a technique of passing a function as a callback to perform processing. This enables advanced replacement processing that cannot be done with just normal regular expression replacement processing.

In re.sub, the syntax is like re.sub([regular expression], [replacement], [text]), but you want to make the “replacement” part programmable and change it, using the group match of the part matched by “regular expression”.

In such cases, you can pass a function or lambda to “replacement” as follows:

(Function)

import re

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

def callback(x):
  return number_mapping[x.group()]

print re.sub(r'\d', callback, "1 testing 2 3")
one testing two three

(Lambda)

import re

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

print re.sub(r'\d', lambda x: number_mapping[x.group()], "1 testing 2 3")
one testing two three

regex - Passing a function to re.sub in Python - Stack Overflow regex - Using a regular expression to replace upper case repeated letters in python with a single lowercase letter - Stack Overflow

Share this article

Shou Arisaka Nov 10, 2025

🔗 Copy Links