Python re.subn Function

The re.subn function in Python's re module performs the same task as re.sub, but also returns the number of substitutions made. This function is useful when you need to know both the result of the substitution and how many substitutions were made.

Table of Contents

  1. Introduction
  2. re.subn Function Syntax
  3. Examples
    • Basic Usage
    • Using Groups in Patterns
    • Using Functions as Replacements
    • Limiting the Number of Substitutions
  4. Real-World Use Case
  5. Conclusion

Introduction

The re.subn function in Python's re module allows you to replace occurrences of a regular expression pattern in a string with a specified replacement string, while also returning the number of substitutions made. This can be particularly useful for logging or debugging purposes.

re.subn Function Syntax

Here is how you use the re.subn function:

import re

result, num_subs = re.subn(pattern, repl, string, count=0, flags=0)

Parameters:

  • pattern: The regular expression pattern to search for.
  • repl: The replacement string or a function that returns the replacement string.
  • string: The string to be processed.
  • count: Optional. The maximum number of pattern occurrences to replace. The default is 0, which means replace all occurrences.
  • flags: Optional. Flags that modify the behavior of the pattern, such as re.IGNORECASE, re.MULTILINE, etc.

Returns:

  • A tuple (result, num_subs) where result is the new string with replacements and num_subs is the number of substitutions made.

Examples

Basic Usage

Here is an example of how to use the re.subn function to replace all digits in a string with a # character and count the substitutions.

Example

import re

# Replacing all digits in a string with '#' and counting the substitutions
result, num_subs = re.subn(r'\d+', '#', 'There are 123 apples and 45 bananas.')
print(result)
print(f"Number of substitutions: {num_subs}")

Output:

There are # apples and # bananas.
Number of substitutions: 2

Using Groups in Patterns

This example demonstrates how to use groups in a regular expression pattern to rearrange parts of the string and count the substitutions.

Example

import re

# Reversing the order of day and month in a date string and counting the substitutions
result, num_subs = re.subn(r'(\d{2})/(\d{2})/(\d{4})', r'\2/\1/\3', 'Today is 12/31/2021.')
print(result)
print(f"Number of substitutions: {num_subs}")

Output:

Today is 31/12/2021.
Number of substitutions: 1

Using Functions as Replacements

This example demonstrates how to use a function as the replacement argument to perform more complex substitutions and count the number of substitutions made.

Example

import re

# Function to replace digits with their squared value
def square(match):
    return str(int(match.group()) ** 2)

# Replacing digits in a string with their squared value and counting the substitutions
result, num_subs = re.subn(r'\d+', square, 'The numbers are 2, 3, and 4.')
print(result)
print(f"Number of substitutions: {num_subs}")

Output:

The numbers are 4, 9, and 16.
Number of substitutions: 3

Limiting the Number of Substitutions

This example demonstrates how to limit the number of substitutions using the count parameter and count the actual number of substitutions made.

Example

import re

# Replacing only the first two occurrences of a digit with '#' and counting the substitutions
result, num_subs = re.subn(r'\d+', '#', 'There are 123 apples, 45 bananas, and 67 cherries.', count=2)
print(result)
print(f"Number of substitutions: {num_subs}")

Output:

There are # apples, # bananas, and 67 cherries.
Number of substitutions: 2

Real-World Use Case

Formatting Phone Numbers and Counting Substitutions

In real-world applications, the re.subn function can be used to format phone numbers and count how many phone numbers were formatted.

Example

import re

def format_phone_numbers(text):
    pattern = r'(\d{3})[-.\s]*(\d{3})[-.\s]*(\d{4})'
    return re.subn(pattern, r'(\1) \2-\3', text)

# Example usage
text = 'Contact us at 123-456-7890, 123.456.7890, or 123 456 7890.'
result, num_subs = format_phone_numbers(text)
print(result)
print(f"Number of phone numbers formatted: {num_subs}")

Output:

Contact us at (123) 456-7890, (123) 456-7890, or (123) 456-7890.
Number of phone numbers formatted: 3

Conclusion

The re.subn function in Python's re module replaces occurrences of a pattern in a string with a specified replacement string and returns the number of substitutions made. This function is useful for performing substitutions and keeping track of how many changes were made. Proper usage of this function can enhance the flexibility and power of your text processing tasks in Python.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare