In this lesson, you will learn how to go beyond static string replacements by using re.sub with callables to perform dynamic, logic-driven text transformations.
Beyond Static Substitution
The re.sub(pattern, repl, string) function is commonly used to swap one string for another. However, when repl is a callable (like a function or a lambda), Python passes a Match object to that function for every successful regex match. This allows you to inspect the captured data, run calculations, or apply conditional logic before returning the replacement string.
Practical Application: Dynamic Transformation
Imagine you have a text file containing prices in USD, and you need to convert them to EUR on the fly. Instead of two-step processing, you can handle the math directly inside the substitution:
import re
def convert_to_eur(match):
# match.group(1) captures the digit portion of the price
usd_price = float(match.group(1))
eur_price = usd_price * 0.92 # Mock exchange rate
return f"€{eur_price:.2f}"
text = "The product costs 10.00 USD, and the shipping is 5.00 USD."
# Use a regex to find numbers followed by 'USD'
# \d+\.\d{2} matches the price, \s+ matches space, 'USD' is the literal
result = re.sub(r'(\d+\.\d{2})\s+USD', convert_to_eur, text)
print(result)
# Output: The product costs €9.20, and the shipping is €4.60.
Why This Matters
Using a callable with re.sub keeps your code clean and memory-efficient. Rather than extracting all matches, storing them in a list, iterating through them, and then reassembling the string, you perform the transformation in a single pass. This is particularly powerful when dealing with complex text formats where the replacement value depends on the context of the match itself.
By utilizing the Match object within the callable, you gain programmatic control over every replacement instance without needing manual loop structures or temporary intermediate collections.
Key Takeaway: Passing a callable to re.sub transforms the substitution process from a static text swap into a dynamic logic engine, allowing you to compute replacement values based on the content of the captured regex groups.