Content · Programming · Python

Python re.sub() Function: Usage and Examples

Replace regular-expression matches using fixed text or a replacement function.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Replace regular-expression matches using fixed text or a replacement function.

How It Works


re.sub(pattern, replacement, string, count=0) returns a new string with nonoverlapping matches replaced. The replacement may be a string with backreferences or a callable that receives each Match.

Step-by-Step Example


import re
redacted_text = re.sub(r'\d{4}', 'XXXX', 'Card 1234; code 5678')
print(redacted_text)
print(re.sub(r'\s+', ' ', 'a   b'))

Understanding the Example


  • The expression "re.sub(r'\\d{4}', 'XXXX', 'Card 1234; code 5678')" supplies the value stored as 'redacted_text'. This value is then used or checked by the later statements.
  • The print() call exposes the result so you can compare it with the behavior described above. Check the value and its type when experimenting.

A successful run of this example prints the following output:

Card XXXX; code XXXX
a b

Where This Fits in a Real Program


Start by writing down examples that should match and examples that must fail. Check whether you need to locate a substring, match a prefix or validate an entire field; these are different operations. Unicode and escape sequences can also change which characters are matched, so test accented text and empty input.

Practice: Try It Yourself


For literal user-provided replacements, a replacement function avoids backslash expansion.

For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.

Further Reading


Read the official Python documentation for complete parameters, return types and exceptions.

Common Beginner Mistakes


  • Passing a replacement containing unintended regex backslash escapes or expecting the original string to change.
  • Mask all numeric four-digit sequences in a test message.

Key Takeaways


  • Replace regular-expression matches using fixed text or a replacement function.
  • re.sub(pattern, replacement, string, count=0) returns a new string with nonoverlapping matches replaced.
  • Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.
Share this resourceSend this page to someone who may find it useful.